Modelesq Modelesq - 1 year ago 29
Python Question

List of dicts: Getting list of matching dictionary based on id

I'm trying to get the matching IDs and store the data into one list. I have a list of dictionaries:

list = [
{'id':'123','name':'Jason','location': 'McHale'},
{'id':'432','name':'Tom','location': 'Sydney'},
{'id':'123','name':'Jason','location':'Tompson Hall'}

Expected output would be something like

# {'id':'123','name':'Jason','location': ['McHale', 'Tompson Hall']},
# {'id':'432','name':'Tom','location': 'Sydney'},

How can I get matching data based on dict ID value? I've tried:

for item in mylist:
list2 = []
row = any(list['id'] == for id in list)

This doesn't work (it throws:
TypeError: tuple indices must be integers or slices, not str
). How can I get all items with the same ID and store into one dict?


First, you're iterating through the list of dictionaries in your for loop, but never referencing the dictionaries, which you're storing in item. I think when you wrote list[id] you mean item[id].

Second, any() returns a boolean (true or false), which isn't what you want. Instead, maybe try row = [dic for dic in list if dic['id'] == item['id']]

Third, if you define list2 within your for loop, it will go away every iteration. Move list2 = [] before the for loop.

That should give you a good start. Remember that row is just a list of all dictionaries that have the same id.