1

Possible Duplicate:
In Python, how to I iterate over a dictionary in sorted order?

I need help in dictionaries. I have two dictionaries, and I want to add the values of identical keys in those two dictionaries. I need to make a list of summing the values that has the same key. I did the list but those values that their keys are the only ones in the two dictionaries are added after finishing all calculations. What I mean is:

dectionary1= {8: 2, 0: 6, 2: 5, 3: 34}  
dectionary2= {8: 6, 1: 2, 3: 2}

My list must be:

summing= [6, 2, 5, 36, 8]

since it will take 0 and check whether there is 0 in dectionary 2, and then it will TAKE 1 (NOT 2) and check whether it's found in dectionary 1 in order to order the list.

I got this so far:

summing=[8, 6, 5, 36, 2]

Here it initially takes key (8) not (0)!! I want it to be in order.

To see my code, that what I got so far:

dic1= {8: 2, 0: 6, 2: 5, 3: 34}  
dic2= {8: 6, 1: 2, 3: 2}
p=[]
for x in dic1:
    if x in dic2:
        g=dic1[x]+dic2[x]
        p=p+[g]
    else:
        p=p+[dic1[x]]
for m in dic2:
    if m in dic1:
        p=p
    else:
        p=p+[dic2[m]]

I think if I can make the dictionaries ascendingly ordered, it will be much easier, but how?

My python is Wing IDE 3.2

Thank you

Community
  • 1
  • 1
  • 1
    `common_keys = set(dic1.keys()) & set(dic2.keys())`. And dict elements are not sorted so you there is no such thing as "in order" for your case. – ThiefMaster Apr 30 '12 at 15:43

1 Answers1

8

You have two options here, one is to use collections.OrderedDict(), but I think the easier option is simply to do it this way:

[dic1.get(x, 0)+dic2.get(x, 0)for x in sorted(dic1.keys() | dic2.keys())]

We first make a set of any keys in either of the dictionaries, sort this into the right order, and then loop over it with a list comprehension, adding the two values (or 0 if the value doesn't already exist).

>>> dic1= {8: 2, 0: 6, 2: 5, 3: 34}  
>>> dic2= {8: 6, 1: 2, 3: 2}
>>> [dic1.get(x, 0)+dic2.get(x, 0)for x in sorted(dic1.keys() | dic2.keys())]
[6, 2, 5, 36, 8]

Note that this only works in 3.x, where dict.keys() returns a set-like dictionary view. If you want to do this in python 2.7.x, use dict.viewkeys() instead, earlier than that, set(dict.iterkeys()) would be optimal.

Gareth Latty
  • 86,389
  • 17
  • 178
  • 183