【发布时间】:2020-08-06 08:18:33
【问题描述】:
是否可以根据参数创建一个返回嵌套字典的函数?
def foo(key):
d = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': 4}, }
return d[key]
foo(['c']['d'])
我在等待:
3
我明白了:
TypeError: list indices must be integers or slices, not str
我了解可以返回整个字典,或对其进行硬编码以返回字典的特定部分,例如
if 'c' and 'd' in kwargs:
return d['c']['d']
elif 'c' and 'e' in kwargs:
return d['c']['e']
但是会很不灵活
【问题讨论】:
-
请查看此链接:Is there a recursive version of the dict.get() built-in?。你得到的错误是由于这个表达式-
['c']['d'],这没有意义。
标签: python