0

I have a problem with keys in a dict in python.I have a list of lists:

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

This is my code:

{(tuple(t[:2])):t[2:] for t in x}

And this is my output:

{('A', 'B'): ['G', 'H']}

The code takes only the last key / value, because there are identical keys.

The output should be:

{('A', 'B'):[['C','D']['E','F'],['G','H']]}

I can't import libraries.

martineau
  • 119,623
  • 25
  • 170
  • 301
lola
  • 235
  • 1
  • 7

2 Answers2

7

You could iterate over the elements and put them in a dictionary according to the key:

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)

Output

{('A', 'B'): [['C', 'D'], ['E', 'F'], ['G', 'H']]}

If the list are sorted by the first two elements, you could use 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)

Output

{('A', 'B'): [['C', 'D'], ['E', 'F'], ['G', 'H']]}
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
4

Use a defaultdict and loop through:

from collections import defaultdict

vals = defaultdict(list)
x=[['A','B','C','D'],['A','B','E','F'],['A','B','G','H']]
for val in x:
    vals[tuple(val[:2])].append(val[2:])

# get rid of default value
vals = dict(vals)
Aplet123
  • 33,825
  • 1
  • 29
  • 55