簡體   English   中英

如何在字典列表中拆分字符串值,以便拆分字符串的每個部分都在其自己的字典中?

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

如何在字典列表中拆分字符串值,以便拆分字符串的每個部分都在其自己的字典中?

例如:

lst = [{item:'321,121,343','name':'abby','amount':'400'},{item:'111,222,333','name':'chris','amount':'500'}]

我希望項目鍵值對的每個部分都在其自己的字典中

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

我沒有運氣嘗試過這個:

[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(","))
]

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

這是一個工作腳本:

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

演示: http//repl.it/RaE

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM