0

I have to compare two dictonaries (unsorted). Threfore I would iterate over one dictonary and If key is in dictA and dictB, then do something with the values. (for example dictA[key] / dict[B])

The dicts looks like: total = {1951: 2, 1952: 2} years = {1922: 33, 1951: 1}

I would except that ratio would be {1951 : 0.5} but instead it is empty.

I have tried various methods. The last one:

for i in total:
            if i in years:
                ratio[i] = years[i] / total[i]

I have also tried to use

year.viewkeys() | total.viewkeys()

But it would just return me the keys, I need to process the values. (Or at least I dont know how atm)

inix42
  • 51
  • 2
  • 8
  • 2
    Could it be that you are using Python 2.x ? If so, check [why doesn't this division work in python](http://stackoverflow.com/questions/1787249/why-doesnt-this-division-work-in-python/1787255#1787255) – fredtantini Jun 09 '15 at 14:02
  • Yeah, python 2.7. Thanks – inix42 Jun 09 '15 at 14:03

3 Answers3

0

You can find which keys are in both dictionaries using set intersection

>>> total = {1951: 2, 1952: 2}
>>> years = {1922: 33, 1951: 1}
>>> common = set(total.viewkeys()).intersection(years.viewkeys())
>>> common
{1951}

Then use a dict comprehension to calculate the ratios

>>> ratio = {i: float(years[i])/float(total[i]) for i in common}
>>> ratio
{1951: 0.5}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

I'm guessing by "instead it is empty", you mean that ratio is {1951: 0}. If you're using Python 2.7, then it's using integer division: 1/2 is truncated down to zero. One possible solution is to convert to float before dividing.

total = {1951: 2, 1952: 2} 
years = {1922: 33, 1951: 1}
ratio = {}
for i in total:
    if i in years:
        ratio[i] = years[i] / float(total[i])

print ratio

Result:

{1951: 0.5}
Kevin
  • 74,910
  • 12
  • 133
  • 166
0
year.viewkeys() | total.viewkeys()

is a very valid approach. try

commonkeys  = year.viewkeys() & total.viewkeys()

instead:

for key in commonkeys:
    ratio[key] = float(year[key]) / total[key]

notice that the float is necessary because in python2, / on integers will lead to 2/3==0.

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94