[英]Python Join 2 dictionaries into 3rd, 2D dictionary where key from dictionary 2 is list value in dictionary 1
I couldn't find this particular python dictionary question anywhere. 我在任何地方都找不到这个特定的python字典问题。
I have two dictionaries: 我有两个字典:
dict1 = {'key1':['val1','val2','val3']}
dict2 = {'val1':['a','b','c']}
I want a 3rd, 2D dictionary with: 我想要具有以下内容的3D,2D词典:
dict3 = {'key1': {'val1':['a','b','c']} }
So, joining 2 dictionaries where the key of the second dictionary is a list value of the first dictionary. 因此,加入2个字典,其中第二个字典的键是第一个字典的列表值。
I was trying some nested looping along the lines of: 我正在尝试一些嵌套循环:
for key1, val1 in dict1.items():
for key2, in val2 in dict2.items():
# do something here
I am not sure if that is the best way to do this. 我不确定这是否是最好的方法。
You can use a dictionary comprehension and then check if the final result contains only one dictionary. 您可以使用字典理解,然后检查最终结果是否仅包含一个字典。 If the latter is true, then a dictionary of dictionaries will be the final result; 如果后者是正确的,那么词典将是最终结果; else, a listing of dictionaries will be stored for the key: 否则,将存储该密钥的词典列表:
dict1 = {'key1':['val1','val2','val3']}
dict2 = {'val1':['a','b','c']}
new_dict = {a:[{i:dict2[i]} for i in b if i in dict2] for a, b in dict1.items()}
last_result = {a:b if len(b) > 1 else b[0] for a, b in new_dict.items()}
Output: 输出:
{'key1': {'val1': ['a', 'b', 'c']}}
This is best done by iterating over dict1
and looking for matching values in dict2
: 最好通过遍历dict1
并在dict1
寻找匹配的值来dict2
:
result = {}
for key, value_list in dict1.items():
result[key] = subdict = {}
for value in value_list:
try:
subdict[value] = dict2[value]
except KeyError:
pass
Result: 结果:
{'key1': {'val1': ['a', 'b', 'c']}}
dict1 = {
'key1':['val1','val2','val3']
}
dict2 = {
'val1':['a','b','c']
}
dict3 = {
key : { val_key : dict2[val_key]
for val_key in val_list if (val_key in dict2.keys())
} for key, val_list in dict1.items()
}
You can try this solution . 您可以尝试此解决方案。
dict1 = {'key1':['val1','val2','val3']}
dict2 = {'val1':['a','b','c']}
join_dict={}
for i,j in dict1.items():
for sub_l,sub_value in dict2.items():
if sub_l in j:
join_dict[i]={sub_l:sub_value}
print(join_dict)
output: 输出:
{'key1': {'val1': ['a', 'b', 'c']}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.