0

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?

2 Answers 2

1

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

That's perfect, now just waiting 10 mins to accept the answer :) Thanks @mtitan8
Great, glad to be of help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.