简体   繁体   English

将单个字典值从字符串转换为整数?

[英]Converting a single dictionary value from string to integer?

Let us consider 让我们考虑一下

set = {'a': '98', 'b': '10', 'c': 'nike', 'd': 'paarudas', 'e': '3'}

I want to change it as, 我想将其更改为

set = {'a': **98**, 'b': **10**, 'c': 'nike', 'd': 'paarudas', 'e': **3**}.

and one more doubt if i get 还有一个怀疑我是否得到

set_1 = {'a': '98', 'b': '10', 'c': 'nike', 'd': 'paarudas', 'e': ''}

Then i have to change it to 然后我必须将其更改为

set_1 = {'a': **98**, 'b': **10**, 'c': 'nike', 'd': 'paarudas', 'e': ''}.
$ python3
>>> s = {'a': '98', 'b': '10', 'c': 'nike', 'd': 'paarudas', 'e': '3'}
>>> {k:int(v) if v.isdigit() else v for k,v in s.items()}
{'a': 98, 'c': 'nike', 'b': 10, 'e': 3, 'd': 'paarudas'}
def int_if_possible(value):
    try: return int(value)
    except: return value

result = dict((k, int_if_possible(v)) for (k, v) in original.items())

Please do not call your variable set ; 请不要调用您的变量set ; that is another data type (like dict ). 那是另一种数据类型(如dict )。

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

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