在字典中,将值从字符串转换为整数

Paa*_*das 15 python string dictionary integer

以下为例:

'user_stats': {'Blog': '1',
                'Discussions': '2',
                'Followers': '21',
                'Following': '21',
                'Reading': '5'},
Run Code Online (Sandbox Code Playgroud)

我想将其转换为:

'Blog' : 1 , 'Discussion': 2, 'Followers': 21, 'Following': 21, 'Reading': 5
Run Code Online (Sandbox Code Playgroud)

Amb*_*ber 16

dict_with_ints = dict((k,int(v)) for k,v in dict_with_strs.iteritems())
Run Code Online (Sandbox Code Playgroud)

  • 请注意[`iteritems`](https://docs.python.org/2/library/stdtypes.html#dict.iteritems)[已经不见了](http://stackoverflow.com/questions/10458437/what-is [Python 3](https://www.python.org/download/releases/3.0/)中的-dict-items-and-dict-iteritems之间的区别.请改用[`items()`](https://docs.python.org/3.7/library/stdtypes.html#dict.items). (5认同)

jco*_*ado 13

您可以使用字典理解:

{k:int(v) for k, v in d.iteritems()}
Run Code Online (Sandbox Code Playgroud)

d带字符串的字典在哪里.

  • @IvanVirabyan你也可以在python 2.7中使用字典理解,因为它们已经被移植了. (2认同)
  • 实际上,该代码仅适用于Python 2.7.`dict.iteritems`在3中消失,因为`dict.items`不再构建列表. (2认同)