dimanche 10 juillet 2016

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'] == list.id for id in list)
    list2.append(row)

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?

Aucun commentaire:

Enregistrer un commentaire