neymar
neymar

Reputation: 213

convert the value of dictionary from list to float

I have a dictionary named "location" like this:

{
    'WA': [
        '47.3917',
        '-121.5708'
    ],
    'VA': [
        '37.7680',
        '-78.2057'
    ],
    ...
}

I want to convert to a dic that the value is a float, so it looks like:

{
    'WA': [
        47.3917,
        -121.5708
    ],
    'VA': [
        37.7680,
        -78.2057
    ],
    ...
}

I tried

for key in location.keys():
    location[key] = float(location[key][0,1])
print location

it gives me an arror that "float() argument must be a string or a number"

how can I fix that?

Upvotes: 3

Views: 5068

Answers (3)

jpp
jpp

Reputation: 164613

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])].

Upvotes: 0

Udy
Udy

Reputation: 2532

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

Upvotes: 3

thefourtheye
thefourtheye

Reputation: 239433

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})

Upvotes: 5

Related Questions