-1

I know variations on this question already exist, but I cannot find one that matches exactly what I am trying to achieve. I have the following code, which included a solution I have taken from a solution to a similar question:

b = {"1":0,"2":0,"3":0,"4":0,"5":0}
c = {"1":1,"4":4,"5":5}

d = [k for k in b if c.get(k, object()) > b[k]]

print d

What I want is to compare all the key and value pairs of the dictionary b with those of c. If a key and value pair is missing from c then the key/pair value of b is retained in the dictionary d, else the values in c are retained in d.

In the example above d should look like this:

d = {"1":1,"2":0,"3":0,"4":4,"5":5}

Can anyone tell me the correct syntax I need for the line d =, please?

Thanks

gdogg371
  • 3,879
  • 14
  • 63
  • 107
  • 1
    The code you posted compares the value `c[k]` with `b[k]`, but your description only refers to present vs. missing, not "only use the value in `c` if it's bigger". What do you want to happen if `c["4"] == -6`? – DSM Jan 11 '15 at 21:27

3 Answers3

2

To answer your actual question

What I want is to compare all the key and value pairs of the dictionary b with those of c. If a key and value pair is missing from c then the key/pair value of b is retained in the dictionary d, else the values in c are retained in d.

>>> b = {"1":0,"2":0,"3":0,"4":0,"5":0}
>>> c = {"1":1,"4":4,"5":5}
>>> d = {k: c.get(k, b[k]) for k in b}
>>> d
{'1': 1, '3': 0, '2': 0, '5': 5, '4': 4}

In Python 3 you should use collections.ChainMap (note this is slightly different in that it will take any key from c, not just the ones in b)

>>> from collections import ChainMap
>>> b = {"1":0,"2":0,"3":0,"4":0,"5":0}
>>> c = {"1":1,"4":4,"5":5}
>>> d = ChainMap(c, b)
>>> d
ChainMap({'1': 1, '5': 5, '4': 4}, {'1': 0, '3': 0, '2': 0, '5': 0, '4': 0})
>>> d['1'], d['2'], d['4']
(1, 0, 4)
jamylak
  • 128,818
  • 30
  • 231
  • 230
0

You need to use an if-elsecondition in your comprehension, and also you dont need to use get when every thing is clear :

>>> d={k:c[k] if k in c and c[k]>b[k] else v for k,v in b.items()}
>>> d
{'1': 1, '3': 0, '2': 0, '5': 5, '4': 4}
Mazdak
  • 105,000
  • 18
  • 159
  • 188
0

Or perhaps this:

b = {"1":0,"2":0,"3":0,"4":0,"5":0}
c = {"1":1,"4":4,"5":5}

d = {k:b[k] if not c.get(k)>b[k] else c[k] for k in b}

d
{'1': 1, '2': 0, '3': 0, '4': 4, '5': 5}

Or, if you want to unpack both key/values from b to compare:

{k:v if not c.get(k)>v else c[k] for k, v in b.iteritems()}

The part of k:v is treated as key=k, and value= v only if k doesn't exist in c and c[k] value is > v, otherwise take v.

And since c.get(k) returns None if k doesn't exist in c, and None > v will automatically translate to False.

Anzel
  • 19,825
  • 5
  • 51
  • 52