I am looking for a way to unpack a list of dictionaries with a certain key ID. I have seen a lot of examples based on a key value, but nothing on just a key match. Say I have a dictionary in the following format returned from a function...
data = [{'Lev1': u'82', 'Marker': u'16', 'TYPE': u'139', 'Location': u'A'},
{'Lev2': u'652', 'Marker': u'1', 'TYPE': u'140', 'Location': u'C'},
{'Lev3': u'452', 'Marker': u'188', 'TYPE': u'141', 'Location': u'B'}]
My current attempt is shown below, but I am getting >> TypeError: list indices must be integers, not str
for item in data:
parts[data['TYPE']].update(data)
The parts
reference above is a dictionary of parts numbers. I am looking to drop each of the following list entries (for example, 'Lev1': u'82', 'Marker': u'16', 'TYPE': u'139', 'Location': u'A'
) into the main 'parts' dictionary based on a TYPE
(there should already be a TYPE match in the parts
dictionary).
My method works for a single returned dictionary entry...
parts[data['TYPE']].update(data)
...but just not with a list of dictionaries.
I am looking to end up with a format along the lines of...
parts{
125:
...
...
...
139:{
'Lev1': u'82',
'Marker': u'16',
'TYPE': u'139',
'Location': u'A'
plus other previously gathered data
}
140:{
'Lev2': u'652',
'Marker': u'1',
'TYPE': u'140',
'Location': u'C'
plus other previously gathered data
}
141:{
'Lev3': u'452',
'Marker': u'188',
'TYPE': u'141',
'Location': u'B'
plus other previously gathered data
}
142:etc
...
}
You can update
with item
instead of data
for item in data:
parts[item['TYPE']].update(item)
Result
>>> parts
{'141': {'Lev3': '452', 'TYPE': '141', 'Marker': '188', 'Location': 'B'},
'140': {'Lev2': '652', 'TYPE': '140', 'Marker': '1', 'Location': 'C'},
'139': {'Lev1': '82', 'Marker': '16', 'Location': 'A', 'TYPE': '139'}}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments