Python 字典列表之间的vlookup

Python vlookup between list of dictionary

我想在两个字典列表之间进行 vlookup,但我不想使用 Pandas,我想使用纯 python 或其他灯库。

所以我有第一个列表:

dict_1 = [{'Name': 'Grant', 'Number': 1111, 'Adress': 'Sal'},
          {'Name': 'Jhon', 'Number': 2222, 'Adress': 'Sal_3'}]

然后我有第二个:

dict_2 = [{'Name': 'Grant', 'High': 3333, 'Tell': 'None1'},
          {'Name': 'Jhon', 'High': 4444, 'Tell': 'None2'}]

因此我想要一个新的字典列表,其中主键是两个列表之间的 'Name'。结果应该是这样的:

[{'Name': 'Grant',
  'Number': 1111,
  'Adress': 'Sal',
  'High': 3333,
  'Tell': 'None1'},
 {'Name': 'Jhon',
  'Number': 2222,
  'Adress': 'Sal_3',
  'High': 4444,
  'Tell': 'None2'}]

你需要一个 main dictName 分组,然后更新值以合并所有字典,最后只保留它的值(合并后的字典)

result = {}
for value in dict_1 + dict_2:
    result.setdefault(value['Name'], {}).update(value)
result = list(result.values())
# after loop
{'Grant': {'Name': 'Grant', 'Number': 1111, 'Adress': 'Sal', 'High': 3333, 'Tell': 'None1'}, 
 'Jhon': {'Name': 'Jhon', 'Number': 2222, 'Adress': 'Sal_3', 'High': 4444, 'Tell': 'None2'}}

# final result
[{'Name': 'Grant', 'Number': 1111, 'Adress': 'Sal', 'High': 3333, 'Tell': 'None1'}, 
 {'Name': 'Jhon', 'Number': 2222, 'Adress': 'Sal_3', 'High': 4444, 'Tell': 'None2'}]

可以用itertools.product()得到两个列表的笛卡尔积,然后只保留匹配'Name'键的字典:

from itertools import product

dict_1 = [{'Name': 'Grant', 'Number': 1111, 'Adress': 'Sal'},
          {'Name': 'Jhon', 'Number': 2222, 'Adress': 'Sal_3'}]
dict_2 = [{'Name': 'Grant', 'High': 3333, 'Tell': 'None1'},
{'Name': 'Jhon', 'High': 4444, 'Tell': 'None2'}]

result = [{**a, **b} for a, b in product(dict_1, dict_2) if a['Name'] == b['Name']]
print(result)

这会打印:

[{'Name': 'Grant', 'Number': 1111, 'Adress': 'Sal', 'High': 3333, 'Tell': 'None1'},
 {'Name': 'Jhon', 'Number': 2222, 'Adress': 'Sal_3', 'High': 4444, 'Tell': 'None2'}]