简体   繁体   English

在 Python 中将嵌套值插入到字典中

[英]Insert nested values into a dictionary in Python

say I have a simple dictionary d={'a':1}说我有一个简单的字典d={'a':1}

I wish to run a line d['b']['c'] = 2 but I can't, I get: KeyError: 'b'我希望运行一行d['b']['c'] = 2但我不能,我得到: KeyError: 'b'

I don't want to insert b first with an empty dictionary because most of the time, this dictionary will contain b with more values except for c .我不想先用空字典插入b ,因为大多数时候,这个字典将包含b ,除了c之外还有更多的值。

Is there an elegant way to do it so my final dictionary is:有没有一种优雅的方法来做到这一点,所以我的最终词典是:

d = {'a':1,
     'b':{'c':2}}

Well if you don't want to first assign an empty dict in order to erase nothing, you can first check if the dict is here or not, it's not one line only but quite clear I think:好吧,如果您不想首先分配一个空的 dict 以便擦除任何内容,您可以先检查 dict 是否在这里,它不仅是一行,而且我认为很清楚:

d ={'a':1}
b = d.get('b', {})
b['c'] = 2
d['b'] = b

Is defaultdict sufficient for you? defaultdict 对你来说足够了吗?

from collections import defaultdict

d = defaultdict()

d['a'] = 1
print(d) # this gives back: defaultdict(None, {'a': 1})

d['b'] = {'c':2}
print(d) # this gives back: defaultdict(None, {'a': 1, 'b': {'c': 2}})

For a better example of defaultdict:有关 defaultdict 的更好示例:

s = 'mississippi'
d = defaultdict(int)
for k in s:
    d[k] += 1

d.items() # this gives back: [('i', 4), ('p', 2), ('s', 4), ('m', 1)]

When a letter is first encountered, it is missing from the mapping, so the default_factory function calls int() to supply a default count of zero.当第一次遇到字母时,映射中缺少它,因此 default_factory 函数调用 int() 以提供默认计数为零。 The increment operation then builds up the count for each letter.增量操作然后建立每个字母的计数。

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

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