Order of iterator


#1

https://www.codecademy.com/courses/python-beginner-en-IZ9Ra/1/2?curriculum_id=4f89dab3d788890003000096

My code has behaved correctly, but i can't understand the order of iterator below because the output has not started from banana but orange:

prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15,
}

for fruit in prices:
    print fruit
    print prices[fruit]
for fruit in stock:
    print fruit
    print stock[fruit]

The above code has returned the following outputs:
orange
1.5
pear
3
banana
4
apple
2
orange
32
pear
15
banana
6
apple
0
None


#2

dictionary's aren't ordered (well, they are, but you don't have control over it)

If you want order, you should use lists


#3

Hi @trtnk ,

If you have a dictionary, and would like to control the order of output, you can create a list of keys, with the keys in your preferred order, then iterate through the list within a loop as you output the information from the dictionary. Following is an example ...

# Capitals.py
# Dictionary of countries and capitals
country_capitals = {"Spain": "Madrid",
            "France": "Paris",
            "Finland": "Helsinki",
            "China": "Beijing",
            "Estonia": "Tallinn",
            "Ghana": "Accra",
            "Sweden": "Stockholm",
            "Australia": "Canberra",
            "Canada": "Ottawa",
            "Ecuador": "Quito",
            "Luxembourg": "Luxembourg",
            "Austria": "Vienna"}

# Save the dictionary keys to a sorted list
countries = sorted(list(country_capitals.keys()))
print("Country    Capital")
print("------------------")
# Use the list to control order of output
for country in countries:
    print("{:10s} {:10s}".format(country, country_capitals[country]))

Output ...

Country    Capital
------------------
Australia  Canberra  
Austria    Vienna    
Canada     Ottawa    
China      Beijing   
Ecuador    Quito     
Estonia    Tallinn   
Finland    Helsinki  
France     Paris     
Ghana      Accra     
Luxembourg Luxembourg
Spain      Madrid    
Sweden     Stockholm

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.