![](/img/trans.png)
[英]Compare the keys of two dictionaries and create a dictionary with key, value pairs that does not match the key in the other dictionary - Python
[英]Python Compare Two Key/Value Pairs
我有两组键值对,如下所示:
tom = {'coffee': 2, 'hotdog': 1}
另一个像这样:
namcat = {'hotdog stand':[hotdog, foodstand], 'cafe':[breakfast, coffee]}
我想在与“ tom”关联的键与“ namcat”中的值相同时进行比较,如果是,则将1加到正在运行的总计中。 我认为它遍历键值对与导致我的问题的列表。
for k, v in namcat.items():
for item in v:
for key, value in tom.items():
if value == item:
running_total += 1
演示:
>>> hotdog = 1
>>> coffee = 2
>>> foodstand = 6
>>> breakfast = 10
>>> tom = {'coffee': 2, 'hotdog': 1}
>>> namcat = {'hotdog stand':[hotdog, foodstand], 'cafe':[breakfast, coffee]}
>>> running_total = 0
>>> for k, v in namcat.items():
for item in v:
for key, value in tom.items():
if value == item:
running_total += 1
>>> running_total
2
这应该做。 希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.