use*_*024 2 python dictionary list python-3.x
我有一个看起来像一个波纹管的列表,有一对重复相同的项目.
l = (['aaron distilled ', 'alcohol', '5'],
['aaron distilled ', 'gin', '2'],
['aaron distilled ', 'beer', '6'],
['aaron distilled ', 'vodka', '9'],
['aaron evicted ', 'owner', '1'],
['aaron evicted ', 'bum', '1'],
['aaron evicted ', 'deadbeat', '1'])
Run Code Online (Sandbox Code Playgroud)
我想将它转换为字典列表,在其中我将第一项的所有重复合并为一个键,因此最终结果如下所示:
data = {'aaron distilled' : ['alcohol', '5', 'gin', '2', 'beer', '6', 'vodka', '9'],
'aaron evicted ': ['owner', '1', 'bum', '1', 'deadbeat', '1']}
Run Code Online (Sandbox Code Playgroud)
我在尝试这样的事情:
result = {}
for row in data:
key = row[0]
result = {row[0]: row[1:] for row in data}
Run Code Online (Sandbox Code Playgroud)
要么
for dicts in data:
for key, value in dicts.items():
new_dict.setdefault(key,[]).extend(value)
Run Code Online (Sandbox Code Playgroud)
但是我得到了错误的结果.我是python的新手,非常感谢有关如何解决这个问题的任何提示,或者参考哪里可以找到允许我这样做的信息.谢谢!
使用collections.defaultdict()对象轻松:
from collections import defaultdict
result = defaultdict(list)
for key, *values in data:
result[key].extend(values)
Run Code Online (Sandbox Code Playgroud)
你的第一次尝试将覆盖密钥; 字典理解不会合并价值观.第二次尝试似乎将列表中的data列表视为dictonaries,因此根本不起作用.
演示:
>>> from collections import defaultdict
>>> data = (['aaron distilled ', 'alcohol', '5'],
... ['aaron distilled ', 'gin', '2'],
... ['aaron distilled ', 'beer', '6'],
... ['aaron distilled ', 'vodka', '9'],
... ['aaron evicted ', 'owner', '1'],
... ['aaron evicted ', 'bum', '1'],
... ['aaron evicted ', 'deadbeat', '1'])
>>> result = defaultdict(list)
>>> for key, *values in data:
... result[key].extend(values)
...
>>> result
defaultdict(<class 'list'>, {'aaron distilled ': ['alcohol', '5', 'gin', '2', 'beer', '6', 'vodka', '9'], 'aaron evicted ': ['owner', '1', 'bum', '1', 'deadbeat', '1']})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2362 次 |
| 最近记录: |