根据特定键拆分列表值

时间:2019-05-02 04:25:57

标签: python

我是Python的新手。

这是一个列表,

list1=[{'A': '4'}, {'D': '4'}, {'B': '2'}, {'A': '3'}, {'D': '3'}, {'C': '3'}, {'E': '3'}, {'E': '4'}, {'D': '3'}, {'D': '2'}, {'D': '1'}]

可以帮我对密钥及其值进行分组吗?例如,对于键D,可以获得D的所有相关值,即4,3,3,21,类似地,对于键A,值{{1} }和4

6 个答案:

答案 0 :(得分:1)

您可以尝试以下方法吗?

all_dict = {}
for d in list1:
    for k, v in d.items():
        if k in all_dict:
            all_dict[k].append(v)
        else:
            all_dict[k] = [v]
print(all_dict)

输出:

{'A': ['4', '3'], 'D': ['4', '3', '3', '2', '1'], 'B': ['2'], 'C': ['3'], 'E': ['3', '4']}

答案 1 :(得分:1)

也尝试一下:

dict_ = {}

for i in list1:
    dict_.setdefault(list(i.keys())[0],[]).append(i[list(i.keys())[0]])

答案 2 :(得分:1)

使用defaultdict

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> list1=[{'A': '4'}, {'D': '4'}, {'B': '2'}, {'A': '3'}, {'D': '3'}, {'C': '3'}, {'E': '3'}, {'E': '4'}, {'D': '3'}, {'D': '2'}, {'D': '1'}]
>>> for e in list1:
...     for k,v in e.items():
...         d[k].append(v)
... 
>>> d
defaultdict(<class 'list'>, {'A': ['4', '3'], 'D': ['4', '3', '3', '2', '1'], 'B': ['2'], 'C': ['3'], 'E': ['3', '4']})
>>> d['B']
['2']
>>> d['A']
['4', '3']
>>> d['D']
['4', '3', '3', '2', '1']

答案 3 :(得分:1)

您可以遍历list1中的字典,并使用dict.setdefault用列表初始化字典中的每个键,以将字典值附加到:

output = {}
for d in list1:
    for k, v in d.items():
        output.setdefault(k, []).append(v)

output变为:

{'A': ['4', '3'], 'D': ['4', '3', '3', '2', '1'], 'B': ['2'], 'C': ['3'], 'E': ['3', '4']}

您还可以安装more-itertools并使用more_itertools.map_reducelist1的键函数和值函数归类,分别返回键和唯一键值对的值子命令:

from more_itertools import map_reduce, first
dict(map_reduce(list1, lambda d: first(d), lambda d: first(d.values())))

这也返回:

{'A': ['4', '3'], 'D': ['4', '3', '3', '2', '1'], 'B': ['2'], 'C': ['3'], 'E': ['3', '4']}

演示:https://repl.it/repls/BeigeGruesomeCylinders

答案 4 :(得分:1)

如果您只想访问相应的值,则只需使用原始列表即可:

list1=[{'A': '4'}, {'D': '4'}, {'B': '2'}, {'A': '3'}, {'D': '3'}, {'C': '3'}, {'E':'3'}, {'E': '4'}, {'D': '3'}, {'D': '2'}, {'D': '1'}]

[e['A'] for e in list1 if 'A' in e]
>>>['4', '3']

答案 5 :(得分:0)

我们需要遍历列表,然后将每个键的所有值附加到列表中

list1=[{'A': '4'}, {'D': '4'}, {'B': '2'}, {'A': '3'}, {'D': '3'}, {'C': '3'}, {'E': '3'}, {'E': '4'}, {'D': '3'}, {'D': '2'}, {'D': '1'}]

dct = {}

#For each key, append all the relevant values to the list
for item in list1:
    for key, value in item.items():
        dct.setdefault(key, [])
        dct[key].append(value)

print(dct)

输出将是

{'A': ['4', '3'], 
'D': ['4', '3', '3', '2', '1'], 
'B': ['2'], 
'C': ['3'], 
'E': ['3', '4']}