如何创建具有相等键的字典?

lol*_*ola 0 python dictionary

我在 python 中的字典中的键有问题。我有一个列表列表:

x=[['A','B','C','D'],['A','B','E','F'],['A','B','G','H']]
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

{(tuple(t[:2])):t[2:] for t in x}
Run Code Online (Sandbox Code Playgroud)

这是我的输出:

{('A', 'B'): ['G', 'H']}
Run Code Online (Sandbox Code Playgroud)

该代码仅采用最后一个键/值,因为有相同的键。

输出应该是:

{('A', 'B'):[['C','D']['E','F'],['G','H']]}
Run Code Online (Sandbox Code Playgroud)

我无法导入库。

Dan*_*ejo 7

您可以遍历元素并根据键将它们放入字典中:

x = [['A', 'B', 'C', 'D'], ['A', 'B', 'E', 'F'], ['A', 'B', 'G', 'H']]

res = {}
for f, s, *tail in x:
    if (f, s) in res:
        res[(f, s)].append(tail)
    else:
        res[(f, s)] = [tail]

print(res)
Run Code Online (Sandbox Code Playgroud)

输出

{('A', 'B'): [['C', 'D'], ['E', 'F'], ['G', 'H']]}
Run Code Online (Sandbox Code Playgroud)

如果列表按前两个元素排序,则可以使用itertools.groupby

from itertools import groupby
from operator import itemgetter

first_two = itemgetter(0, 1)

x = [['A', 'B', 'C', 'D'], ['A', 'B', 'E', 'F'], ['A', 'B', 'G', 'H']]

res = {k : [e[2:] for e in group] for k, group in groupby(x, first_two)}
print(res)
Run Code Online (Sandbox Code Playgroud)

输出

{('A', 'B'): [['C', 'D'], ['E', 'F'], ['G', 'H']]}
Run Code Online (Sandbox Code Playgroud)