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

例如:

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

===============>>#1 票数:1 已采纳

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

===============>>#2 票数:0

这是一个工作脚本:

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

  ask by Chris translate from so

未解决问题?本站智能推荐: