Reputation: 1725
I am trying to iterate over a multidimensional list in Python but it is not acting as I would expect.
POIs = {'GTA': {'areas': [{'lat': 43.7, 'range': '40km', 'long': -79.416}]}, 'Montreal': {'areas': [{'lat': 45.509, 'range': '40km', 'long': -73.588}]}}
for POI in POIs:
print POI
This returns strings
GTA
Montreal
If I did a similar thing using .each in Ruby it would pass the hash. Is there a fundamental difference in how Python and Ruby deal with array loops? Or is there a better way to try and achieve .each style iteration in Python?
Upvotes: 0
Views: 136
Reputation: 493
This is a dictionary rather than a list, so you're printing the keys in your example. You can print the values as well with the following code:
for POI in POIs:
print POI, POIs[POI]
Upvotes: 1
Reputation: 22882
If you want the values in addition to the keys when iterating over a dictionary, use .items()
or .iteritems()
. The important point here is you have a dictionary, rather than a multi-dimensional list
(a multi-dimensional list would look like L = [[1, 2, 3], [4, 5, 6]]
).
POIs = {'GTA': {'areas': [{'lat': 43.7, 'range': '40km', 'long': -79.416}]}, 'Montreal': {'areas': [{'lat': 45.509, 'range': '40km', 'long': -73.588}]}}
for POI, areas in POIs.iteritems():
print POI, areas
Output
GTA {'areas': [{'lat': 43.7, 'range': '40km', 'long': -79.416}]}
Montreal {'areas': [{'lat': 45.509, 'range': '40km', 'long': -73.588}]}
Upvotes: 1