dictionary - Unpacking a list of dictionaries based on key matches in Python -
i looking way unpack list of dictionaries key id. have seen lot of examples based on key value, nothing on key match. have dictionary in following format returned 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 shown below, getting >> typeerror: list indices must integers, not str
for item in data: parts[data['type']].update(data) the parts reference above dictionary of parts numbers. looking drop each of following list entries (for example, 'lev1': u'82', 'marker': u'16', 'type': u'139', 'location': u'a') main 'parts' dictionary based on type (there should type match in parts dictionary).
my method works single returned dictionary entry...
parts[data['type']].update(data) ...but not list of dictionaries.
i looking end format along lines of...
parts{ 125: ... ... ... 139:{ 'lev1': u'82', 'marker': u'16', 'type': u'139', 'location': u'a' plus other gathered data } 140:{ 'lev2': u'652', 'marker': u'1', 'type': u'140', 'location': u'c' plus other gathered data } 141:{ 'lev3': u'452', 'marker': u'188', 'type': u'141', 'location': u'b' plus other gathered data } 142:etc ... }
you can update 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'}}
Comments
Post a Comment