【问题标题】:In dictionary, converting the value from string to integer在字典中,将值从字符串转换为整数
【发布时间】:2012-03-02 17:19:31
【问题描述】:

以下面的例子为例:

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

我想把它转换成:

'Blog' : 1 , 'Discussion': 2, 'Followers': 21, 'Following': 21, 'Reading': 5

【问题讨论】:

    标签: python string dictionary integer


    【解决方案1】:
    dict_with_ints = dict((k,int(v)) for k,v in dict_with_strs.iteritems())
    

    【讨论】:

    【解决方案2】:

    您可以使用dictionary comprehension

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

    d 是带有字符串的字典。

    【讨论】:

    • @IvanVirabyan 您还可以在 python 2.7 中使用字典推导,因为它们已被向后移植。
    • 事实上,该代码仅适用于 Python 2.7 。 dict.iteritems 在 3 中消失了,因为 dict.items 不再构建列表。
    【解决方案3】:
    >>> 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}
    

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 2021-05-02
        • 1970-01-01
        • 2012-03-26
        • 1970-01-01
        • 2015-04-21
        • 1970-01-01
        • 2017-06-11
        • 2015-07-04
        • 1970-01-01
        相关资源
        最近更新 更多