简体   繁体   中英

How to split string values across a list of dictionaries, so that each part of the split string is in it's own dictionary?

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
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'}
]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM