[英]Compare two dictionaries keys and create dictionary with list values in Python
Let's say you have two different dictionaries. 假设您有两个不同的字典。
info_stored = {'a' : 0, 'b' : 2, 'c' : 15}
log_stored = {'dog' : 1, 'a' : 1, 'ted' : 14}
I want to compare these 2 dictionaries to determine if keys are matched. 我想比较这两个字典以确定键是否匹配。 Only 'a' is common in this example.
在此示例中,仅'a'是常见的。
for key in info_stored:
if key in log_stored:
I want to create a new dictionary with the common key and a list of the values from that common key. 我想用公共密钥和该公共密钥的值列表创建一个新的字典。
common_stored = {'a' : [0, 1]}
How about this: 这个怎么样:
info_stored = {'a' : 0, 'b' : 2, 'c' : 15}
log_stored = {'dog' : 1, 'a' : 1, 'ted' : 14}
common_stored = {k: [] for k in info_stored if k in log_stored}
and then: 接着:
for key in common_stored:
common_stored[k].extend([info_stored[k], log_stored[k]])
print(common_stored) # common_stored = {'a' : [0, 1]}
The first step is about creating a dictionary with the common elements as keys and empty lists as values. 第一步是创建一个字典,以公共元素为键,空列表为值。
Finally we modify these empty lists based on the contents of the original dicts. 最后,我们根据原始字典的内容修改这些空列表。
You can even combine the two steps in a single dictionary comprehension as follows: 您甚至可以将两个步骤合并为一个字典,如下所示:
common_stored = {k: [info_stored[k], log_stored[k]] for k in info_stored if k in log_stored}
info_stored = {'a' : 0, 'b' : 2, 'c' : 15}
log_stored = {'dog' : 1, 'a' : 1, 'ted' : 14}
common_stored = {}
# Traverse through info_stored dictionary
for key, val in info_stored.items():
# Check for key in log_stored dictionary, if found add it to common_stored
if key in log_stored:
common_stored[key] = [val, log_stored[key]]
common_stored
{'a': [0, 1]}
a simple solution would be this: 一个简单的解决方案是这样的:
info_stored = {'a' : 0, 'b' : 2, 'c' : 15}
log_stored = {'dog' : 1, 'a' : 1, 'ted' : 14}
result={}
for key in info_stored :
if key in log_stored :
result[key]=[ info_stored[key], log_stored[key]]
print (result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.