-1

i have a question please; i have two lists like this

my_inital_list=  [{"name": "Tom", "age": 30},
  {"name": "Mark", "age": 25},
  {"name": "Pam", "age": 97}]

my_second_list =   [{"name": "Pam", "quant": 10},
  {"name": "Mark", "quant": 5},
  {"name": "Tom", "quant": 7}]

can you please explain to me how can convert theme to something like this without using nested loops

my_final_list=  [{"name": "Tom", "age": 30,"quant": 7},
  {"name": "Mark", "age": 25,"quant": 5},
  {"name": "Pam", "age": 97, "quant": 10}
]
  • Welcome to SO! What have you tried so far? Why can't you use a nested loop? We're much more here to help with specific questions of the form "I tried X, but it did not do what I expect and instead resulted in an error!" accompanied by a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – ti7 Nov 01 '21 at 22:26
  • as i mentioned, nested loops for ... for but i'm looking for something more pythonic, i'm trying to imrove my self – bellami molinka Nov 01 '21 at 22:28

1 Answers1

0

Use a dictionary to avoid the nested for-loop used for matching:

# create a lookup dictionary 
lookup = {d["name"]: d for d in my_second_list}

# merge the dictionaries using lookup
res = [{**d, **lookup[d["name"]]} for d in my_inital_list]
print(res)

Output

[{'name': 'Tom', 'age': 30, 'quant': 7}, {'name': 'Mark', 'age': 25, 'quant': 5}, {'name': 'Pam', 'age': 97, 'quant': 10}]

The lookup dictionary maps the values of the "name" in my_second_list to it's own dictionary:

{'Pam': {'name': 'Pam', 'quant': 10}, 'Mark': {'name': 'Mark', 'quant': 5}, 'Tom': {'name': 'Tom', 'quant': 7}}

then you can use it to fetch the data by name, for example:

lookup["Pam"]  # returns lookup["Pam"]

then simply iterate over each dictionary on my_initial_list using a list comprehension and merge the corresponding dictionaries using the expression below:

{**d, **lookup[d["name"]]}
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76