简体   繁体   中英

How can I add all values from a tuple into a dictionary?

Say I have a list of three-tuples and I want a function to add them into a nested dictionary two layers deep for example:

lst = [('Watermelon', 200, (1,4)), ('Apple', 100, (2, 23)), ('Apple', 120, (1, 33))]

and I want to return a dictionary f that looks like:

f = {'Watermelon': {(1,4): 200}, 'Apple': {(2, 23): 100, (1, 33): 120 }}

This will work. No imports required and is more readable than the comprehension-type syntax.

dictionary = {}
for a, b, c in lst:
    if a not in dictionary:
        dictionary[a] = {}
    dictionary[a][c] = b

EDIT

  1. Agree with DavidBurke. Comprehensions are indeed intuitive and readable. They should not be taken too far, though. ;)

Feel free to make corrections. This answer has come to the top so it shouldn't be misleading.

import collections as co

dd = co.defaultdict(dict)

for item in lst: 
    dd[item[0]].update({item[2]:item[1]}) 

Result:

In [31]: dd
Out[31]: 
defaultdict(dict,
            {'Watermelon': {(1, 4): 200},
             'Apple': {(2, 23): 100, (1, 33): 120}})

Simplest syntax:

{a: {c: b} for a, b, c in lst}

This is a dictionary generation that outputs a: {c: b} for each item in list, unpacking them in sequential order as a, b, c .

This doesn't get quite what you want, as you have common keys that you want turned into a list. Other answers do that, less elegant as they are and must be. I'm leaving this here to help any future Googler who doesn't have quite the same requirement you do.

from collections import defaultdict


keys = [name for name, *_ in lst]
vals = [pair for _, *pair in lst]

f = defaultdict(dict)

for key, val in zip(keys, vals):
    f[key].update({val[1]: val[0]})

Result:

 defaultdict(dict, {'Watermelon': {(1, 4): 200}, 'Apple': {(2, 23): 100, (1, 33): 120}})

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