首页 > python > 使用另一个字典中的项替换字典中列表中的项

使用另一个字典中的项替换字典中列表中的项 (Replacing items in a list in a dictionary with items from another dictionary)

问题

我有以下词典:

d1 = {"00f_5" :[1,2,3], "00f_6": [1,2,3]}

d2 = [{"marker":"00f_5",1: 'AAA'},{"marker":"00f_6", 1: 'CCC'},{"marker":"00f_5", 2:"AAC"}]

我想要以下输出:

d1 = {"00f_5" :["AAA","AAC",3], "00f_6": ["CCC",2,3]}

我尝试了多次尝试,但我无法得到它。任何帮助将非常感激。

解决方法

您可以构建一个将标记映射到将数字键映射到3个字母代码的子字典的字典,以便给定标记和数字键,您可以使用dict.get方法获取映射的代码(如果存在):

d = {}
for s in d2:
    d.setdefault(s['marker'], {}).update(s)
d1 = {k: [d[k].get(i, i) for i in l] for k, l in d1.items()}

所以给出:

d1 = {"00f_5" :[1,2,3], "00f_6": [1,2,3]}
d2 = [{"marker":"00f_5",1: 'AAA'},{"marker":"00f_6", 1: 'CCC'},{"marker":"00f_5", 2:"AAC"}]

d1 会变成:

{'00f_5': ['AAA', 'AAC', 3], '00f_6': ['CCC', 2, 3]}

问题

I have the following dictionaries:

d1 = {"00f_5" :[1,2,3], "00f_6": [1,2,3]}

d2 = [{"marker":"00f_5",1: 'AAA'},{"marker":"00f_6", 1: 'CCC'},{"marker":"00f_5", 2:"AAC"}]

I would like the following output:

d1 = {"00f_5" :["AAA","AAC",3], "00f_6": ["CCC",2,3]}

I have tried multiple attempts, but I couldn't get it. Any help would be much appreciated.

解决方法

You can build a dict that maps the marker to a sub-dict that maps numeric keys to the 3-letter codes, so that given a marker and a numeric key, you can use dict.get method to get the mapped code if it exists:

d = {}
for s in d2:
    d.setdefault(s['marker'], {}).update(s)
d1 = {k: [d[k].get(i, i) for i in l] for k, l in d1.items()}

so that given:

d1 = {"00f_5" :[1,2,3], "00f_6": [1,2,3]}
d2 = [{"marker":"00f_5",1: 'AAA'},{"marker":"00f_6", 1: 'CCC'},{"marker":"00f_5", 2:"AAC"}]

d1 will become:

{'00f_5': ['AAA', 'AAC', 3], '00f_6': ['CCC', 2, 3]}
相似信息