在嵌套字典中将python中的字典值从str转换为int [英] Converting dictionary values in python from str to int in nested dictionary
本文介绍了在嵌套字典中将python中的字典值从str转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前有一个嵌套的字典,看起来像这样:
I currently have a nested dictionary which looks like this:
series = {
'a': {'foo':'2', 'bar':'3', 'baz':'7', 'qux':'1'},
'b': {'foo':'6', 'bar':'4', 'baz':'3', 'qux':'0'},
'c': {'foo':'4', 'bar':'5', 'baz':'1', 'qux':'6'}
}
我正在尝试将字符串中的值转换为整数.
And I'm trying to convert the values from strings into integers.
我尝试过这种方法:
newseries = dict((k,int(v)) for k,v in series.items())
但是我得到的只是一条错误消息:
But all I get is an error message saying:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict'
我在做什么错了?
推荐答案
在这种情况下,您必须更深入:
You have to go deeper in this case:
In [4]: {k: {kk: int(vv) for kk, vv in v.items()}
for k, v in series.items()}
Out[4]:
{'a': {'bar': 3, 'baz': 7, 'foo': 2, 'qux': 1},
'b': {'bar': 4, 'baz': 3, 'foo': 6, 'qux': 0},
'c': {'bar': 5, 'baz': 1, 'foo': 4, 'qux': 6}}
您自己的示例仅迭代系列的键,值对,该键具有(嵌套的) dict
值.
Your own example just iterates the key, value -pairs of series, which has (nested) dict
values.
请注意,这不是通用解决方案.为此,您需要递归或堆栈.
Note that this is not a generic solution. For that you'd need recursion or a stack.
这篇关于在嵌套字典中将python中的字典值从str转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文