Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

python - list to dictionary conversion with multiple values per key?

I have a Python list which holds pairs of key/value:

l = [[1, 'A'], [1, 'B'], [2, 'C']]

I want to convert the list into a dictionary, where multiple values per key would be aggregated into a tuple:

{1: ('A', 'B'), 2: ('C',)}

The iterative solution is trivial:

l = [[1, 'A'], [1, 'B'], [2, 'C']]
d = {}
for pair in l:
    if pair[0] in d:
        d[pair[0]] = d[pair[0]] + tuple(pair[1])
    else:
        d[pair[0]] = tuple(pair[1])

print(d)

{1: ('A', 'B'), 2: ('C',)}

Is there a more elegant, Pythonic solution for this task?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
from collections import defaultdict

d1 = defaultdict(list)

for k, v in l:
    d1[k].append(v)

d = dict((k, tuple(v)) for k, v in d1.items())

d contains now {1: ('A', 'B'), 2: ('C',)}

d1 is a temporary defaultdict with lists as values, which will be converted to tuples in the last line. This way you are appending to lists and not recreating tuples in the main loop.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...