Home > database >  Python vlookup between list of dictionary
Python vlookup between list of dictionary

Time:03-16

I want to do a vlookup between two list of dictionary, but I don´t want to use Pandas, I would like to use pure python or some another light library.

So I have the first one list:

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

And then I have the second one:

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

And I want as a result a new list of dictionary where the main key is 'Name' between the two lists. The result should be something like:

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

CodePudding user response:

You need a main dict to group by the Name, then update the value to merge all dict, finally keep only the values of it (the merged dict)

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'}]

CodePudding user response:

You can use itertools.product() to obtain the Cartesian product between the two lists, then retain only the dictionaries which match on the 'Name' key:

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)

This prints:

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