[英]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
= 给出
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 演示: http : //repl.it/RaE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.