【问题标题】:How to split string values across a list of dictionaries, so that each part of the split string is in it's own dictionary?如何在字典列表中拆分字符串值,以便拆分字符串的每个部分都在它自己的字典中?
【发布时间】:2014-04-20 02:11:41
【问题描述】:

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

例如:

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

【问题讨论】:

  • 这个例子是lst = [{item:'321,121,343','name':'abby','amount':'400'},{item:'111,222,333','name':'chris','amount':'500'}]吗?
  • 你确定你不想使用 key : value 为 '321' : dict 的字典吗?也就是每一个item值都是一个key,其中value是一个dict?
  • Eli Rose,你是对的。人类,我明白你的意思,但这不是我的字典

标签: python list dictionary


【解决方案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】:

    这是一个工作脚本:

    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

    【讨论】:

    • 唯一的问题是我的实际字典列表中的键值对比这多得多,因此将每个键都写出来既烦人又费时。我想知道是否有办法绕过这方面,所以我不必写出'name'键值对或'amount'键值对。
    猜你喜欢
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多