【问题标题】:Python. Get {key:value} from dictionary in list and set it to another dict in listPython。从列表中的字典中获取 {key:value} 并将其设置为列表中的另一个字典
【发布时间】:2017-05-21 22:17:23
【问题描述】:

我正在研究我的问题的答案,但我还没有找到解决方案。 我有两个清单。列表的元素是字典。仅当字典与另一个 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

更新: 即使具有相同 'A' 值的 dict 具有不同的索引,它也应该可以工作:

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 的两个字典共享一个密钥会发生什么?
  • @WillemVanOnsem 1. 检查每个字典中'A' 的值(比较list_1 的字典和list_2 的字典) 2. 如果list_2 中的字典中'A' 的值相等到list_1 中字典中'A' 的值 3. 从list_1 中的字典中获取另一个key:value(例如'C':3)并将其附加到list_2 中的适当字典中抱歉,如果我解释得不够清楚,但我再好不过了:)

标签: python dictionary


【解决方案1】:

如果我做对了,这就是你想要的

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)

出来: [{'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)

【讨论】:

  • 谢谢,但如果 dic 有不同的索引,它就不起作用。例如,如果list_2[1] 有'A':1 和list_1[0] 有'A':1
  • 如果 list_2[1] 有 'A':1 并且 list_1[0] 有 'A':1 应该是什么输出??
  • 我已经更新了我的询问并为此案例添加了输出。请看。
【解决方案2】:

这是一个单行,假设密钥 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)]

【讨论】:

  • (1) 不能一起添加字典; (2) 在这里你硬编码C 并假设A 和B 总是在字典中。
  • (1) 是的……不知道是怎么回事。 (2) 是的,这些是假设......我会编辑。
【解决方案3】:
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)

【讨论】:

  • 不幸的是,如果适当的字典有不同的索引,它就不起作用。请在我的问题中查看更新信息
猜你喜欢
  • 2020-11-25
  • 2016-09-14
  • 2020-03-26
  • 1970-01-01
  • 1970-01-01
  • 2016-01-21
  • 2016-01-10
  • 1970-01-01
  • 2013-06-19
相关资源
最近更新 更多