[英]Compare the key/values of two dictionaries and put into new dictionary
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
. 我想要的是将字典b
所有键和值对与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
. 如果一个键和值的对从丢失c
然后的键/对值b
被保留在字典d
,否则在值c
保留在d
。
In the example above d
should look like this: 在上面的示例中, d
应该看起来像这样:
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? 谁能告诉我d =
行所需的正确语法?
Thanks 谢谢
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. 我想要的是将字典b的所有键和值对与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. 如果c中缺少键和值对,则b的键/对值将保留在字典d中,否则c中的值将保留在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
) 在Python 3中,您应该使用collections.ChainMap
(请注意,这将略有不同,因为它将使用c
任何键,而不仅仅是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)
You need to use an if-else
condition in your comprehension, and also you dont need to use get
when every thing is clear : 您需要在理解中使用if-else
条件,并且当每件事都清楚时也不需要使用get
:
>>> 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}
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: 或者,如果要从b
解压缩两个键/值以进行比较:
{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
. k的部分:V是视为key=k
,和value=
v
仅当k
不存在c
和c[k]
值是>
v
,否则取v
。
And since c.get(k)
returns None if k
doesn't exist in c, and None > v
will automatically translate to False . 并且由于c.get(k)
如果c中不存在k
则返回None ,并且None > v
将自动转换为False 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.