简体   繁体   English

如何用另一个字典值替换字典的值

[英]how to replace values of dictionary with another dictionary values

Hi I have two lists which contain some dictionary with their values嗨,我有两个列表,其中包含一些带有它们的值的字典

list1 = [{'val-1': 0, 'val-2': 0, 'val-3': 0}, {'val-1': 0, 'val-2': 0, 'val-3': 0}, {'val-4': 0, 
'val-5': 0, 'val-6': 0}]

list2 = [{'val-1': 90, 'val-4': 89, 'val-3': 99}, {'val-2': 88, 'val-6': 55, 'val-1':100}]

The desired output would be something like this所需的 output 将是这样的

output: [{'val-1': 90, 'val-2': 88, 'val-3': 99}, {'val-1': 90, 'val-2': 88, 'val-3': 99}, {'val-4': 
89,'val-5': 0, 'val-6': 55}]

How could I make this replacement?我怎么能做这个替换?

what I did form list2 I select each dictionary and compare and replace the values present in list1 all dictionary我在 list2 中做了什么我 select 每个字典并比较和替换 list1 所有字典中存在的值

but I didn't get the correct output但我没有得到正确的 output

From the list2 you may build a unique dict that holds the transformation mappings, if you have more than once occurence of a key you have 2 choiceslist2中,您可以构建一个包含转换映射的唯一dict ,如果您不止一次出现一个键,您有 2 个选择

  1. keep first occurence, don't overwrite保持第一次出现,不要覆盖
  2. keep last, overwrite each time保持最后,每次覆盖

For keepfirst对于keepfirst

list2 = [{'val-1': 90, 'val-4': 89, 'val-3': 99}, {'val-2': 88, 'val-6': 55, 'val-1': 100}]

# 1. Keep first (in fact overwrite but do backward)
update_dict = {k: v for d in list2[::-1] for k, v in d.items()}
# 2. Keep last
update_dict = {k: v for d in list2 for k, v in d.items()}

Then rebuild the original list1 structure with list and dict comprehension, using the update_dict然后用 list 和 dict 理解重建原始list1结构,使用update_dict

result = [{k: update_dict.get(k, v) for k, v in subdict.items()}
          for subdict in list1]
print(result)

With 1. keep first 1. keep first

[{'val-1': 90, 'val-2': 88, 'val-3': 99}, {'val-1': 90, 'val-2': 88, 'val-3': 99}, {'val-4': 89, 'val-5': 0, 'val-6': 55}]

With 2. keep last (changes val-1 ) 2. keep last (更改val-1

[{'val-1': 100, 'val-2': 88, 'val-3': 99}, {'val-1': 100, 'val-2': 88, 'val-3': 99}, {'val-4': 89, 'val-5': 0, 'val-6': 55}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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