Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Creating a dict from list of key, value tuples while maintaining duplicate keys

So I've got a comprehension to the effect of:

dict((x.key, x.value) for x in y)

The problem, of course, is that if there's multiple x.keys with the same value, they get collapsed with the last x.value with that particular x.key as the only surviving member. I want to actually make the values of the resulting dict a list:

{
    'key1': ['value1'],
    'key2': ['value2', 'value3', 'value4'],
    'key3': ['value5'],
    # etc.
}

Is this logic possible with a comprehension?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can add the elements one by one to a dictionary that contains empty lists by default:

import collections

result_dict = collections.defaultdict(list)
for x in y:
    result_dict[x.key].append(x.value)

You can also do something very similar without having to use the collections module:

result_dict = {}
for x in y:
    result_dict.setdefault(x.key, []).append(x.value)

but this is arguably slightly less legible.

An equivalent, more legible (no need to "parse" the less common setdefault) but more pedestrian, base Python approach is:

result_dict = {}
for x in y:
    if x.key not in result_dict:
        result_dict[x.key] = []
    result_dict[x.key].append(x.value)

The first solution is clearly the preferred one, as it is at the same time concise, legible, and fast.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...