简体   繁体   English

如何按键合并 Python 字典?

[英]How can I merge Python dictionaries by keys?

Let's say I got two dictionaries in a list looks like below:假设我在列表中有两个字典,如下所示:

[
    {'country': 'United Kingdom',
    'city': 'Cambridge',
    'title': 'University of Cambridge',
    'region': 'Europe'},
    {'country': 'United States',
    'city': 'Cambridge',
    'title': 'Institute of Technology (MIT)',
    'region': 'North America'}
]

and I also have another two dictionaries (for each university's location) in a list below:我在下面的列表中还有另外两本词典(针对每所大学的位置):

[
    {'title': 'University of Cambridge',
    'latitude': '52.1873962',
    'longitude': '0.1302958635475542'},
    {'title': 'Institute of Technology (MIT)',
    'latitude': '42.3582393',
    'longitude': '-71.09664602558988'},
]

How can combine these two lists to:如何将这两个列表合并为:

[
    {'country': 'United Kingdom',
    'city': 'Cambridge',
    'title': 'University of Cambridge',
    'region': 'Europe',
    'latitude': '52.1873962',
    'longitude': '0.1302958635475542'},
    {'country': 'United States',
    'city': 'Cambridge',
    'title': 'Institute of Technology (MIT)',
    'region': 'North America', 
    'latitude': '42.3582393',
    'longitude': '-71.09664602558988'}
]

What is the syntactically cleanest way to accomplish this?实现此目的的语法最简洁的方法是什么?

Thanks for any help!!谢谢你的帮助!!

You can use zip() to pair off the dicts then merge them in a comprehension with something like:您可以使用zip()来配对字典,然后将它们合并为类似以下内容的理解:

d1 = [
    {'country': 'United Kingdom',
    'city': 'Cambridge',
    'title': 'University of Cambridge',
    'region': 'Europe'},
    {'country': 'United States',
    'city': 'Cambridge',
    'title': 'Institute of Technology (MIT)',
    'region': 'North America'}
]

d2 = [
    {'title': 'University of Cambridge',
    'latitude': '52.1873962',
    'longitude': '0.1302958635475542'},
    {'title': 'Institute of Technology (MIT)',
    'latitude': '42.3582393',
    'longitude': '-71.09664602558988'},
]

[{**a,**b} for a,b in zip(d1, d2)]

Which will give you:这会给你:

[{'country': 'United Kingdom',
  'city': 'Cambridge',
  'title': 'University of Cambridge',
  'region': 'Europe',
  'latitude': '52.1873962',
  'longitude': '0.1302958635475542'},
 {'country': 'United States',
  'city': 'Cambridge',
  'title': 'Institute of Technology (MIT)',
  'region': 'North America',
  'latitude': '42.3582393',
  'longitude': '-71.09664602558988'}]

Let's say I got two dictionaries in a list looks like below:假设我在一个列表中有两个字典,如下所示:

[
    {'country': 'United Kingdom',
    'city': 'Cambridge',
    'title': 'University of Cambridge',
    'region': 'Europe'},
    {'country': 'United States',
    'city': 'Cambridge',
    'title': 'Institute of Technology (MIT)',
    'region': 'North America'}
]

and I also have another two dictionaries (for each university's location) in a list below:我在下面的列表中还有另外两本词典(针对每所大学的位置):

[
    {'title': 'University of Cambridge',
    'latitude': '52.1873962',
    'longitude': '0.1302958635475542'},
    {'title': 'Institute of Technology (MIT)',
    'latitude': '42.3582393',
    'longitude': '-71.09664602558988'},
]

How can combine these two lists to:如何将这两个列表结合起来:

[
    {'country': 'United Kingdom',
    'city': 'Cambridge',
    'title': 'University of Cambridge',
    'region': 'Europe',
    'latitude': '52.1873962',
    'longitude': '0.1302958635475542'},
    {'country': 'United States',
    'city': 'Cambridge',
    'title': 'Institute of Technology (MIT)',
    'region': 'North America', 
    'latitude': '42.3582393',
    'longitude': '-71.09664602558988'}
]

What is the syntactically cleanest way to accomplish this?实现此目的的语法上最干净的方法是什么?

Thanks for any help!!谢谢你的帮助!!

You can merge two dictionaries using **kwargs您可以使用**kwargs合并两个词典

unis = [
    {'country': 'United Kingdom',
    'city': 'Cambridge',
    'title': 'University of Cambridge',
    'region': 'Europe'},
    {'country': 'United States',
    'city': 'Cambridge',
    'title': 'Institute of Technology (MIT)',
    'region': 'North America'}
]

locs = [
    {'title': 'University of Cambridge',
    'latitude': '52.1873962',
    'longitude': '0.1302958635475542'},
    {'title': 'Institute of Technology (MIT)',
    'latitude': '42.3582393',
    'longitude': '-71.09664602558988'},
]

combined_list = []
for i, v in enumerate(unis):
    combined_dict = {**v, **locs[i]}
    combined_list.append(combined_dict)

print(combined_list) outputs (formatted for visibility): print(combined_list)输出(格式化为可见性):

[
    {'country': 'United Kingdom',
     'city': 'Cambridge',
     'title': 'University of Cambridge',
     'region': 'Europe',
     'latitude': '52.1873962',
     'longitude': '0.1302958635475542'},

    {'country': 'United States',
     'city': 'Cambridge', 
     'title': 'Institute of Technology (MIT)', 
     'region': 'North America', 
     'latitude': '42.3582393', 
     'longitude': '-71.09664602558988'}
]

Since we are to merge, we do not know the order in which the dictionaries appear nor can we claim that the first list is equivalent in length to the second list.由于我们要合并,我们不知道字典出现的顺序,也不能声称第一个列表的长度与第二个列表的长度相等。 Thus:因此:

first = [
    {'country': 'United Kingdom',
    'city': 'Cambridge',
    'title': 'University of Cambridge',
    'region': 'Europe'},
    {'country': 'United States',
    'city': 'Cambridge',
    'title': 'Institute of Technology (MIT)',
    'region': 'North America'}
]
second = [
    {'title': 'University of Cambridge',
    'latitude': '52.1873962',
    'longitude': '0.1302958635475542'},
    {'title': 'Institute of Technology (MIT)',
    'latitude': '42.3582393',
    'longitude': '-71.09664602558988'},
]

a = {j['title']:j for j in second}
[{**i, **a[i['title']]} for i in first]

[{'city': 'Cambridge',
  'country': 'United Kingdom',
  'latitude': '52.1873962',
  'longitude': '0.1302958635475542',
  'region': 'Europe',
  'title': 'University of Cambridge'},
 {'city': 'Cambridge',
  'country': 'United States',
  'latitude': '42.3582393',
  'longitude': '-71.09664602558988',
  'region': 'North America',
  'title': 'Institute of Technology (MIT)'}]

This works using perge.这可以使用 perge。

for i in range(len(x)):x[i].update(y[i])

output output

[{'country': 'United Kingdom', 'city': 'Cambridge', 'title': 'University of Cambridge', 'region': 'Europe', 'latitude': '52.1873962', 'longitude': '0.1302958635475542'}, {'country': 'United States', 'city': 'Cambridge', 'title': 'Institute of Technology (MIT)', 'region': 'North America', 'latitude': '42.3582393', 'longitude': '-71.09664602558988'}]```

If we assume that the order of the two lists might not always match, we cant just zip the lists together.如果我们假设两个列表的顺序可能并不总是匹配,我们就不能将 zip 列表放在一起。 Create a dict to allow O(1) look up of university data on the title element.创建一个字典以允许 O(1) 在 title 元素上查找大学数据。

Then iterate the countries and if you find the matching title in the look up dict, merge the dicts.然后迭代国家,如果你在查找字典中找到匹配的标题,合并字典。

countries = [
    {'country': 'United Kingdom',
    'city': 'Cambridge',
    'title': 'University of Cambridge',
    'region': 'Europe'},
    {'country': 'United States',
    'city': 'Cambridge',
    'title': 'Institute of Technology (MIT)',
    'region': 'North America'}
]

universities = [
    {'title': 'University of Cambridge',
    'latitude': '52.1873962',
    'longitude': '0.1302958635475542'},
    {'title': 'Institute of Technology (MIT)',
    'latitude': '42.3582393',
    'longitude': '-71.09664602558988'},
]

unidict = {u['title']: u for u in universities}
result = [{**c, **unidict[c['title']]} for c in countries if c['title'] in unidict]
print(result)

Result结果

[{'country': 'United Kingdom', 'city': 'Cambridge', 'title': 'University of Cambridge', 'region': 'Europe', 'latitude': '52.1873962', 'longitude': '0.1302958635475542'}, {'country': 'United States', 'city': 'Cambridge', 'title': 'Institute of Technology (MIT)', 'region': 'North America', 'latitude': '42.3582393', 'longitude': '-71.09664602558988'}]

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

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