首页 > 解决方案 > 从另一个字典python更新列表字典

问题描述

我有两个字典列表:我正在尝试将 test2 与 test1 进行比较并相应地更新。

test1 = [{'names': ['a', 'b', 'c'],
  'country': 'USA',
  'state': 'Texas'},

 {'names': ['d', 'e', 'f'],
  'country': 'Australia',
  'state': 'Melbourne'},

 {'names': ['i', 'j', 'k'],
  'country': 'canada',
  'state': 'Toronto'},

 {'names': ['l', 'm', 'n'],
  'country': 'Austria',
  'state': 'Burgenland'}]

test2 = [{'code': 4286,
'list_of_countries': ['USA',
            'Australia',
            'Colombia',
            'Denmark',
            'Greece',
            'Iceland']},
 {'code':4287,
 'list_of_countries': ['Texas',
            'Argentina',
            'Austria',
            'Bangladesh', 'canada']}]

预期输出:

test2 = [{'names':['a', 'b', 'c', 'd', 'e', 'f'],
        'country': ['USA', 'Australia'],
        'state': ['Texas', 'Melbourne'],
        'code':4286},

        {'names':['i', 'j', 'k', 'l', 'm', 'n'],
        'country': ['canada', 'Austria'],
        'state': ['Toronto','Burgenland'],
        'code':4287}]

尝试以下片段:通过在 test2 list_of_countries 中搜索 test1 国家:

for i in test1:
    for j in test2:
        a = []
        if i.get('country') in j.get('list_of_countries'):
           a.append({'country':i.get('country'), 'state':i.get('state'})
           j.update(a)

标签: python

解决方案


您可以转换test2为字典,将每个条目list_of_countries与其正确的键相关联。然后,您可以使用此结果进行分组:

test2 = [{'code': 4286, 'list_of_countries': ['USA', 'Australia', 'Colombia', 'Denmark', 'Greece', 'Iceland']}, {'code': 4287, 'list_of_countries': ['Texas', 'Argentina', 'Austria', 'Bangladesh', 'canada']}]
test1 = [{'names': ['a', 'b', 'c'], 'country': 'USA', 'state': 'Texas'}, {'names': ['d', 'e', 'f'], 'country': 'Australia', 'state': 'Melbourne'}, {'names': ['i', 'j', 'k'], 'country': 'canada', 'state': 'Toronto'}, {'names': ['l', 'm', 'n'], 'country': 'Austria', 'state': 'Burgenland'}]
d = {i:k['code'] for k in test2 for i in k['list_of_countries']}

现在,您可以创建一系列defaultdict与国家代码关联的 s。通过在 中循环国家/州字典test1,您可以保持与每个代码关联的州和国家/地区的运行更新:

from collections import defaultdict
new_d = dict(zip(d.values(), [defaultdict(list) for _ in d]))
for i in test1:
   for a, b in i.items():
     new_d[d[i['country']]][a].append(b)

r = [{'code':a, **b, 'names':[j for k in b['names'] for j in k]} for a, b in new_d.items()]

最终的列表理解转换new_d为您想要的格式,即字典列表。

输出:

[{'code': 4286, 'names': ['a', 'b', 'c', 'd', 'e', 'f'], 'country': ['USA', 'Australia'], 'state': ['Texas', 'Melbourne']}, {'code': 4287, 'names': ['i', 'j', 'k', 'l', 'm', 'n'], 'country': ['canada', 'Austria'], 'state': ['Toronto', 'Burgenland']}]

推荐阅读