pythondictionarypython-2.6

Setting order in Dictionary


I am a beginner in Python . dont know how can i set the order in Dictionary? . i searched and came to know it could be done through from collections import OrderedDict but don't know how to use it. i am trying below mention code to compare two Dictionary but i am not getting the output in order .

d = { k[0]: k[1:] for k in a }
d2= { k[0]: k[1:] for k in b }
p = {i:j for i,j in d2.items() if i not in d} 
q = {i:j for i,j in d.items() if i not in d2}

Any idea how to do this ?

Updated Question :

i have a nested list . How to get each list of nested list in next line ?

[['Eth116/1/12        sales            connected 1         full    10G     Fabric Exte'], ['Eth116/1/13   marketing        connected 190       full    100                ']]

Expected Output :

Eth116/1/12        sales            connected 1         full    10G     Fabric Exte
Eth116/1/13   marketing        connected 190       full    100                

Solution

  • Dictionaries are unordered and there is not much you can do to change that, short of writing your own subclass of dict (not recommended). Using OrderedDict will work, as shown in hiro protagonists's comment, as long as you keep in mind that the order in an OrderedDict is the order of insertion and is not related to the values of the keys. (The same is true of the ordering of Python 3 dicts.) If a and b have the same elements but in a different order then the resulting OrderedDicts will not be equal, unless you sort a and b beforehand.

    If you want to compare two dicts where you can't easily determine the order of insertion, you need a data structure that supports unordered comparisons. I didn't have your data so I had to make some up. I started with this input

    >>> a
    [[1, 3, 5, 7, 9], [4, 9, 14, 19, 24, 29, 34, 39], [8, 17, 26, 35, 44, 53, 62, 71], [9, 19, 29, 39, 49, 59, 69, 79, 89]]
    >>> b
    [[1, 3, 5, 7, 9], [4, 9, 14, 19, 24, 29, 34, 39], [8, 17, 26, 35, 44, 53, 62, 71]]
    

    As you can see, a has one extra element beginning 9.

    Modify your dictionary construction code to make the values tuples not lists, because the dict values need to be hashable for the next step to work:

    >>> d = { k[0]: tuple(k[1:]) for k in a }
    >>> d2= { k[0]: tuple(k[1:]) for k in b }
    

    Then you can convert the dictionaries to sets to do an unordered comparison:

    >>> s = set(d.items())
    >>> s2 = set(d2.items())
    >>> s == s2
    False
    

    And you can use the set operators to discover what the difference is:

    >>> s2 <= s
    True
    >>> s - s2
    set([(9, (19, 29, 39, 49, 59, 69, 79, 89))])