1

I have a location name and then a latitude and longitude for each location. I'm trying to determine the best way to express a single key with two values in Python. I was thinking this:

dict = {
    'California': ('36.46715833333333', '-117.85891388888888'),
    'California2': ('36.46715833333333', '-117.85891388888888'),
}

Then to add more:

dict['California'] = ('36.46715833333333', '-117.85891388888888')

But then how would I easily iterate through each and extract them?

for location in dict:
    for lat, lon in location:
        print lat, lon

This gives a ValueError stating it does not have more than one value to unpack. How do I iterate through this and get each lat and long?

4

2 回答 2

6

遍历 dict 对象会遍历其键。您必须明确获取值:

for location in d:
    lat, long = d[location]

或使用.items()

for name, location in d.items():
    lat, long = location

或者使用元组解包:

for name, (lat, long) in d.items():
    ...

另外,不要命名你的字典dict。您正在遮蔽内置函数dict(并且long,但您可能不会注意到)。

于 2013-05-23T15:16:33.873 回答
1

正如另一个答案所述,迭代 dict 只会获取键而不是值。以您想要的方式迭代的最直接方法:

for lat, lon in d.itervalues():

要获得所有三个:

for location, (lat, lon) in d.iteritems():
于 2013-05-23T15:19:44.633 回答