将字典的值更改为整数

这个问题在这里已经有了答案:

  • 如何在Python中将字符串解析为float或int? 22个答案

  • >>> old =  {'Georgia': ['18', '13', '8', '14']}
    >>> new = {key: list(map(int, value)) for key, value in old.items()}
    >>> new
    {'Georgia': [18, 13, 8, 14]}
    

    你可以这样做:

    map在这种情况下将迭代器中的值作为字典键的值,并将迭代器中的每个项都转换为intmap返回一个地图对象而不是一个list所以我们将它转​​换回列表。

    a_dict = {'Georgia': ['18', '13', '8', '14']}
    a_dict['Georgia'] = list(map(int, a_dict['Georgia']))
    

    或者,如果您需要以这种方式转换多个值,则可以使用循环:

     for k,v in list(a_dict.items()):
         a_dict[k] = list(map(int, v))
    
    链接地址: http://www.djcxy.com/p/48433.html

    上一篇: Changing values of dictionary to integers

    下一篇: max() not finding actual maximum value in list