简体   繁体   中英

Python dictionary comprehension: assign value to key, where value is a list

Example:

dictionary = {"key":[5, "string1"], "key2":[2, "string2"], "key3":[3, "string1"]}

After applying this dict comprehension:

another_dictionary = {key:value for (value,key) in dictionary.values()}

The result is like this:

another_dictionary = {"string1": 5, "string2": 2}

In other words, it doesn't sum up integer values under the same key which was a list item.

=================================================================

Desired result:

another_dictionary = {"string1": 8, "string2": 2}

You can use collections.defaultdict for this:

from collections import defaultdict

dictionary = {"key":[5, "string1"], "key2":[2, "string2"], "key3":[3, "string1"]}

d = defaultdict(int)

for num, cat in dictionary.values():
    d[cat] += num

print(d)

defaultdict(<class 'int'>, {'string1': 8, 'string2': 2})

The reason your code does not work is you have not specified any summation or aggregation logic. This will require either some kind of grouping operation or, as here, iterating and adding to relevant items in a new dictionary.

You can also use itertools.groupby :

import itertools
dictionary = {"key":[5, "string1"], "key2":[2, "string2"], "key3":[3, "string1"]}
d= {a:sum(c for _, [c, d] in b) for a, b in itertools.groupby(sorted(dictionary.items(), key=lambda x:x[-1][-1]), key=lambda x:x[-1][-1])}

Output:

{'string2': 2, 'string1': 8}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM