简体   繁体   中英

Python. Get {key:value} from dictionary in list and set it to another dict in list

I was researching answer for my question, but I have not found a solution. I have two lists. Elements of the lists are dictionaries. I want to get key:value from first list only if a dictionary has equal another key:value . Example:

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: It should be working even if dict with the same value of 'A' has different indices:

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_1list_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)]

if i get it right this is what you want

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}]

UPDATE: I implemented as a function and added the functionality you want,check if it ok..

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM