gpt4 book ai didi

python - 在 Python 中将嵌套值插入字典中

转载 作者:行者123 更新时间:2023-12-01 00:02:55 24 4
gpt4 key购买 nike

假设我有一个简单的字典d={'a':1}

我希望运行一行 d['b']['c'] = 2 但我不能,我得到:KeyError: 'b'

我不想首先插入带有空字典的 b ,因为大多数时候,该字典将包含 b 以及除 c 之外的更多值.

有没有一种优雅的方法来做到这一点,所以我的最终字典是:

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

最佳答案

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}})

有关 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)]

当第一次遇到某个字母时,映射中缺少该字母,因此 default_factory 函数调用 int() 来提供默认计数为零。然后,增量操作会累积每个字母的计数。

关于python - 在 Python 中将嵌套值插入字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60203778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com