I have a dictionary named \"location\" like this:
{
\'WA\': [
\'47.3917\',
\'-121.5708\'
],
\'VA\': [
\'37.7680\',
\'
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
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])]
.
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})