繁体   English   中英

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

[英]In dictionary, converting the value from string to integer

以下为例:

'user_stats': {'Blog': '1',
                'Discussions': '2',
                'Followers': '21',
                'Following': '21',
                'Reading': '5'},

我想将其转换为:

'Blog' : 1 , 'Discussion': 2, 'Followers': 21, 'Following': 21, 'Reading': 5
dict_with_ints = dict((k,int(v)) for k,v in dict_with_strs.iteritems())

您可以使用字典理解

{k:int(v) for k, v in d.iteritems()}

其中d是带字符串的字典。

>>> d = {'Blog': '1', 'Discussions': '2', 'Followers': '21', 'Following': '21', 'Reading': '5'}
>>> dict((k, int(v)) for k, v in d.iteritems())
{'Blog': 1, 'Discussions': 2, 'Followers': 21, 'Following': 21, 'Reading': 5}

以免任何人被这个页面误导 - Python 2和3中的字典文字当然可以直接使用数值。

embed={ 'the':1, 'cat':42, 'sat':2, 'on':32, 'mat':200, '.':4 }
print(embed['cat']) # 42

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM