convert the value of dictionary from list to float

前端 未结 3 1531
陌清茗
陌清茗 2021-01-21 11:00

I have a dictionary named \"location\" like this:

{
    \'WA\': [
        \'47.3917\',
        \'-121.5708\'
    ],
    \'VA\': [
        \'37.7680\',
        \'         


        
相关标签:
3条回答
  • 2021-01-21 11:31

    Your problem is in here: float(location[key][0,1])

    # float objects are length 1
    for key in location.keys():
        location[key] = [float(location[key][0]),float(location[key][1])]
    print location
    
    0 讨论(0)
  • 2021-01-21 11:41

    You can use a list comprehension within a dictionary comprehension. Since you need both keys and values, use dict.items to iterate key-value pairs:

    res = {k: [float(x) for x in v] for k, v in locations.items()}
    

    map works more efficiently with built-ins, so you may wish to use:

    res = {k: list(map(float, v)) for k, v in locations.items()}
    

    Or, since you have coordinates, for tuple values:

    res = {k: tuple(map(float, v)) for k, v in locations.items()}
    

    The problem with your logic location[key][0,1] is Python lists do not support vectorised indexing, so you need to be explicit, e.g. the verbose [float(location[key][0]), float(location[key][1])].

    0 讨论(0)
  • 2021-01-21 11:45

    You can use dictionary comprehension to construct a dictionary which has the values converted to floats, like this

    print {k:map(float, locations[k]) for k in locations}
    

    As suggested by @Grijesh in the comments section, if you are using Python 3,

    print({k:list(map(float, locations[k])) for k in locations})
    
    0 讨论(0)
提交回复
热议问题