Search code examples
pythonpython-2.7listsetordereddictionary

Convert OrderedDict to set in python


I have an OrderedDict like this:

OrderedDict([
    (1666, [
        ['2ZNV', 'EDO1', 14, '2FCN', 'CD', 119],
        ['2ZNV', 'EDO', 14, '2FCN', 'CD', 119]]), 
    (1056, [['2ZNV', 'EDO', 32, '2FCN','CD', 33]]), 
    (266, [['2ZNV', 'EDO', 14, '2FCN', 'CD', 19]]), 
    (171, [
        ['2ZNV', 'ZN', 9, '2FCN', 'DVA', 19], 
        ['2ZNV', 'ZN', 9, '2FCN', 'CD', 19], 
        ['2ZNV', 'ZN', 9, '2FCN', 'ACT', 19], 
        ['2ZNV', 'EDO', 9, '2FCN', 'CD', 19], 
        ['2ZNV', 'EDO', 9, '2FCN', 'DVA', 19]]),
    (45, [
        ['2ZNV','EDO', 9, '2X8L', 'GOL', 5], 
        ['2ZNV', 'ZN', 9, '2X8L', 'GOL', 5]]),
    (6, [['2ZNV', 'EDO', 2, '2FCN', 'CD', 3]]), 
    (1, [['2ZNV', 'EDO', 1, '2FCN', 'CD', 1]])
])

Is it possible to add all the values in a set but keep the ordering?

I tried to convert to list and then from tuple to set like this:

for k,v in od.items():
    listset.append(v)
flat = [item for sublist in listset for item in sublist]
xx = set(tuple(x) for x in flat)
print xx

but this is not keep the ordering. The result of the above is:

set([
    ('2ZNV', 'ZN', 9, '2FCN', 'DVA', 19),
    ('2ZNV', 'EDO', 14, '2FCN', 'CD', 119),
    ('2ZNV', 'EDO', 9, '2X8L', 'GOL', 5),
    ('2ZNV', 'EDO', 32, '2FCN', 'CD', 33),
    ('2ZNV', 'EDO', 9, '2FCN', 'DVA', 19),
    ('2ZNV', 'ZN', 9, '2FCN', 'ACT', 19),
    ('2ZNV', 'EDO', 9, '2FCN', 'CD', 19),
    ('2ZNV', 'EDO', 1, '2FCN', 'CD', 1),
    ('2ZNV', 'EDO', 14, '2FCN', 'CD', 19),
    ('2ZNV', 'ZN', 9, '2X8L', 'GOL', 5),
    ('2ZNV', 'EDO1', 14, '2FCN', 'CD', 119),
    ('2ZNV', 'EDO', 2, '2FCN', 'CD', 3),
    ('2ZNV', 'ZN', 9,'2FCN', 'CD', 19)
])

Thank you in advance.


Solution

  • You can use OrderedSet from this recipe https://code.activestate.com/recipes/576694/. Just

    OrderedSet([tuple(item) for sublist in od.values() for item in sublist])