Python 修改嵌套字典中的值
这是我的密码Python 修改嵌套字典中的值,python,Python,这是我的密码 def increase_by_one(d): for key, value in d.items(): if d[value] == type(int): ## There is an error here d[value] = d[value] + 1 else: d[key] += 1 return d 我不确定出了什么问题。但是我确信如果d[value]==type(int)是
def increase_by_one(d):
for key, value in d.items():
if d[value] == type(int): ## There is an error here
d[value] = d[value] + 1
else:
d[key] += 1
return d
我不确定出了什么问题。但是我确信如果d[value]==type(int)是错误的。我怎样才能改变它
输入
输出
{'a':{'b':{'c':11}}}
{'1':3.7, '11':17, '111':{'a':6, 't':9}}
输入
increase_by_one({'1':2.7, '11':16, '111':{'a':5, 't':8}})
输出
{'a':{'b':{'c':11}}}
{'1':3.7, '11':17, '111':{'a':6, 't':9}}
您正在按值编制索引,但应该使用键,无需从字典中获取值,因为您已经在使用
items()
:
根据您的建议,以下是我为您提供所需解决方案的答案:
def increase_by_one(d):
for key in d:
try:
d[key] += 1
except TypeError:
d[key] = increase_by_one(d[key])
return d
每次尝试向字典添加1时,都会引发TypeError
。因为您知道您正在处理嵌套字典,所以再次调用函数。这叫做递归
>>> increase_by_one({'a':{'b':{'c':10}}})
{'a': {'b': {'c': 11}}}
>>> increase_by_one({'1':2.7, '11':16, '111':{'a':5, 't':8}})
{'1': 3.7, '11': 17, '111': {'a': 6, 't': 9}}
首先使用
isinstance()
和iteritems()
但当您处理嵌套的dict时,这就不行了。使用递归或者如果你知道dict的深度,首先做一个检查,比如
isinstance(value,dict)
d[key]
保存值,而不是d[value]
提示:type(int)==type
和type(aNumber)==int
。我还没有被教过尝试:除了TypeError:我可以知道它是如何工作的吗?而且,即使1被添加到值中,但我意识到对于{'first':27,'second':16,'third':8},当我通过函数{'first':28,'third':9,'second':17}传递它时,返回的是{'first':27,'second':16,'third':8},并且键的顺序发生了变化。我可以知道为什么吗?你可以通过阅读有关的书籍来自学。字典是无序的数据结构,不能依赖它们来确定顺序。如果需要订货,我们有订单。
for key, value in d.iteritems():
if isinstance(value,int):
...