![](/img/trans.png)
[英]How to add values from one dictionary to another based on matching keys?
[英]Matching the values of one dictionary to the keys of another dictionary (Python)
晚上所有,
希望你一切都好。
我的目標我試圖將一個字典的值與另一個字典的鍵匹配。
dict1
有鍵但沒有值dict2
有鍵和值
dict2
的值可以作為dict1
中的鍵找到。 我正在嘗試編寫代碼來識別 dict2 中的哪些值與dict2
中的鍵匹配。
我的嘗試注釋代碼如下。
dict1 = {('dict1_key1',): [], ('dict1_key2',): []} #dictionary with keys, but no values;
for i in dict2.keys(): #iterate through the keys of dict2
for x in dict2[i]: #reaching every element in tuples in dict2
if x == dict1.keys(): #if match found in the name of keys in dict1
print(f"{i} holding {x}.") #print which key and value pair in dict 2 match the keys in dict1
如果我按如下方式編寫for loop
,則代碼有效:
for i in dict2.keys(): #iterate through the keys of dict2
for x in dict2[i]: #reaching every element in tuples in dict2
if x == dict1_key1 or x == dict1_key2(): #if match found in the name of keys in dict1
print(f"{i} holding {x}.") #print which key and value pair in dict 2 match the keys in dict1
但是,實際上dict1
需要能夠包含不同數量的鍵,這就是為什么我希望if x == dict1.keys():
可以工作的原因。
任何反饋將不勝感激。
@馬克邁耶
根據要求的示例值:
dict1 = {('Tower_001',): [], ('Tower_002'): []}
dict2 = {1: 'Block_A', 'Tower_001'] #first key in dict2
#skipping keys 2 through 13
{14: ['Block_N', 'Tower_002']#last key in dict2
您可以設置dict1.keys
和dict2.value
中的所有值。 然后只需取這些集合的交集即可找到也是值的鍵:
dict1 = {('Tower_001',): [], ('Tower_005',): [], ('Tower_002',): []}
dict2 = {1: ['Block_A', 'Tower_001'], #first key in dict2
14: ['Block_N', 'Tower_002']} #last key in dict2
set(k for l in dict2.values() for k in l) & set(k for l in dict1.keys() for k in l)
# {'Tower_001', 'Tower_002'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.