Reputation: 5804
How to split string values across a list of dictionaries, so that each part of the split string is in it's own dictionary?
For example:
lst = [{item:'321,121,343','name':'abby','amount':'400'},{item:'111,222,333','name':'chris','amount':'500'}]
I'd like each part of the item key-value pair to be in its own dictionary
Desired_List = [{item:'321','name':'abby','amount':'400'},{item:'121','name':'abby','amount':'400'},{item:'343','name':'abby','amount':'400'},{item:'111','name':'chris','amount':'500'},{item:'222','name':'chris','amount':'500'},{item:'333','name':'chris','amount':'500'}]
I've tried this with no luck:
[li.update({li['item']:spl}) for li in lst for spl in li['item'].split(',')]
return Li
Upvotes: 0
Views: 65
Reputation: 56654
def unpack_dict(d, field, unpack):
packed = d.pop(field)
for item in unpack(packed):
result = d.copy()
result[field] = item
yield result
lst = [
{'item':'321,121,343','name':'abby','amount':'400'},
{'item':'111,222,333','name':'chris','amount':'500'}
]
new_lst = [
ud
for d in lst
for ud in unpack_dict(d, "item", lambda item: item.split(","))
]
gives new_lst
=
[
{'amount': '400', 'item': '321', 'name': 'abby'},
{'amount': '400', 'item': '121', 'name': 'abby'},
{'amount': '400', 'item': '343', 'name': 'abby'},
{'amount': '500', 'item': '111', 'name': 'chris'},
{'amount': '500', 'item': '222', 'name': 'chris'},
{'amount': '500', 'item': '333', 'name': 'chris'}
]
Upvotes: 1
Reputation: 32189
Here is a working script:
lst = [{'item':'321,121,343','name':'abby','amount':'400'}, {'item':'321,121,343','name':'chris','amount':'500'}]
new_list = [{'item':j, 'name': i['name'], 'amount': i['amount']} for i in lst for j in i['item'].split(',')]
>>> print new_list
[{item:'321','name':'abby','amount':'400'},{item:'121','name':'abby','amount':'400'},{item:'343','name':'abby','amount':'400'},{item:'111','name':'chris','amount':'500'},{item:'222','name':'chris','amount':'500'},{item:'333','name':'chris','amount':'500'}]
Demo: http://repl.it/RaE
Upvotes: 0