简体   繁体   English

如何将元组中的所有值添加到字典中?

[英]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:假设我有一个三元组列表,我想要一个 function 将它们添加到嵌套字典中,例如两层深:

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 ,它看起来像:

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 .这是一个字典生成,它为列表中的每个项目输出a: {c: b} ,按顺序将它们解包为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}})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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