Python: If key in dictA exist and key dictB do something

111 Views Asked by At

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)

3

There are 3 best solutions below

0
On

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}
0
On

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}
0
On
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.