Changing values of dictionary to integers

This question already has an answer here:

  • How do I parse a string to a float or int in Python? 22 answers

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

    You can do this:

    map is taking the values from the iterable in this case the value of the dictionaries key and casting every item in the iterable to an int . map returns a map object instead of a list so we are converting it back to a list.

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

    Or, if you need to convert multiple values this way you can use a loop:

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

    上一篇: 我如何解决这个恼人的错误信息? (Python 3.6.1)

    下一篇: 将字典的值更改为整数