[英]Python. Get {key:value} from dictionary in list and set it to another dict in list
我正在研究問題的答案,但沒有找到解決方案。 我有兩個清單。 列表的元素是字典。 我想key:value
從第一個列表只有在字典里等於另一個key:value
。 例:
list_1 = [{'A':1, 'B':2, 'C':3}, {'A':10, 'B':20, 'C':30}]
list_2 = [{'A':1, 'B':22,}, {'A':111, 'B':20}]
# I need get key and value of 'C' from list_1 IF value of 'A' in both dict are equal
# code block for my task...
# result
list_2 = [{'A':1, 'B':22, 'C':3}, {'A':111, 'B':20}]
# 'C':3 append in list_2[0], because 'A' has same value
UPD:即使具有相同“ A”值的字典具有不同的索引,它也應該起作用:
list_1 = [{'A':1, 'B':2, 'C':3}, {'A':10, 'B':20, 'C':30}]
list_2 = [{'A':111, 'B':20}, {'A':1, 'B':22,}]
# code...
# result
list_2 = [{'A':111, 'B':20}, {'A':1, 'B':22, 'C':3}]
這是一個襯里,它假定鍵A在list_1
和list_2
中的所有字典中,而C在list_1
所有字典中:
list_2 = [dict(l2, C=l1['C']) if l1['A'] == l2['A'] else l1 for l1, l2 in zip(list_1, list_2)]
如果我做對了這就是你想要的
list_1 = [{'A':1, 'B':2, 'C':3}, {'A':10, 'B':20, 'C':30}]
list_2 = [{'A':1, 'B':22,}, {'A':111, 'B':20}]
for dic in range(len(list_1)):
if list_1[dic]['A']==list_2[dic]['A']:
list_2[dic]['C']=list_1[dic]['C']
print(list_2)
out: [{'A': 1, 'B': 22, 'C': 3}, {'A': 111, 'B': 20}]
更新:我實現為一個功能,並添加了所需的功能,請檢查是否正常。
def add_to_other_list(list_1,list_2):
for dic_1 in list_1:
for dic_2 in list_2:
if dic_1['A']==dic_2['A']:
dic_2['C']=dic_1['C']
return list_2
list_2 = add_to_other_list(list_1,list_2)
def copymatch (matchkey, copykey, source, target):
if source.get(matchkey) == target.get(matchkey):
target[copykey] = source.get(copykey)
for source, target in zip(list_1,list_2):
copymatch('A','C',source,target)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.