简体   繁体   English

如何在不覆盖前一个键的情况下合并列表中的两个字典

[英]How to merge two dictionaries in a list without overwriting the previous key

For the dictionaries in a list, I need to extract and merge them in a single dictionary without overwriting the existing key values.对于列表中的字典,我需要在不覆盖现有键值的情况下将它们提取并合并到一个字典中。

For example, I have:例如,我有:

mylist = [{'b': 3}, {'b': 9, 'A': 8, 'Z': 2, 'V': 1}]

The result should be:结果应该是:

{'b': 3, 'A': 8, 'Z': 2, 'V': 1}

Below is my code:下面是我的代码:

def concatenate_dict(dict_list: list) -> dict:
    final_dict = {}
    for d in dict_list:
        for k, v in d.items():
            if k not in final_dict:
                final_dict |= (k, v)

    return final_dict


mylist = [{'b': 7}, {'b': 10, 'A': 8, 'Z': 2, 'V': 1}]
print(concatenate_dict(mylist))

I do not understand why the "not in" keyword would not skip the existing 'b': 10 item and leave 'b': 7 alone and continue to 'A': 8我不明白为什么“不在”关键字不会跳过现有的 'b': 10 项并留下 'b': 7 单独并继续 'A': 8

Instead of iterating over every dictionary, how about reverse mylist and iteratively update an output dictionary?与其遍历每个字典,不如反向mylist并迭代update output 字典? Then every key-value pair inserted into out from the back will be updated from the front if a key already exists.然后,如果键已经存在,则从后面插入out的每个键值对都将从前面更新。

out = {}
for d in mylist[::-1]:
    out.update(d)

Output: Output:

{'b': 3, 'A': 8, 'Z': 2, 'V': 1}

Fix使固定

Use the appropriate operator, you can't use |= with a tuple使用适当的运算符,不能将|=与元组一起使用

def concatenate_dict(dict_list: list) -> dict:
    final_dict = {}
    for d in dict_list:
        for k, v in d.items():
            if k not in final_dict:
                final_dict[k] = v
    return final_dict

Improve提升

Iterate on the dicts backwards and use dict.update向后迭代字典并使用dict.update

def concatenate_dict(dict_list: list) -> dict:
    final_dict = {}
    for d in reversed(dict_list):
        final_dict.update(d)
    return final_dict

Could be with reduce and merge operator可以使用reduce和 merge 运算符

from functools import reduce

def concatenate_dict(dict_list: list) -> dict:
    return reduce(lambda x, y: x | y, reversed(dict_list))

I think the best way to do it, both in terms of readability and efficiency, is to iterate on your dicts in reverse order, as suggested in the Improve section of azro's answer .我认为,就可读性和效率而言,最好的方法是按照azro's answer的“改进”部分中的建议,以相反的顺序迭代你的 dicts。

However, I'd like to highlight methoddict.setdefault , which does exactly what you want: add a key: value to a dict, only if the key wasn't already in the dict.但是,我想突出显示方法dict.setdefault ,它完全符合您的要求:将key: value添加到 dict 中,前提是该键尚未在 dict 中。

def concatenate_dict(dict_list: list) -> dict:
    final_dict = {}
    for d in dict_list:
        for k, v in d.items():
            final_dict.setdefault(k, v)
    return final_dict


mylist = [{'b': 7}, {'b': 10, 'A': 8, 'Z': 2, 'V': 1}]
print(concatenate_dict(mylist))
# {'b': 7, 'A': 8, 'Z': 2, 'V': 1}

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

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