Looping and Dictionaries

If you use a dictionary as the sequence in a for statement, it traverses the key of the dictionary. The example is shown below.
guitars = {'gibson': 5050, 'fender': 500, 'jackson': 2000}
for key in guitars:
    print key, guitars[key]
After executing the code the result is.
jackson 2000
fender 500
gibson 5050
If we want to find all the entries in a dictionary above thousand, we could write the following code:
guitars = {'gibson': 5050, 'fender': 500, 'jackson': 2000}
for key in guitars:
    if guitars[key] > 1000:
        print key, guitars[key]
The result after executing previous block of code is:
jackson 2000
gibson 5050
We only see entries of the dictionary with value above 1000. If you want to print keys in alphabetical order, you first make a list of keys in the dictionary using keys method available in dictionary objects, and then sort that list and loop through the sorted list, looking up each key printing out key/value pairs in sorted order as follows:
guitars = {'gibson': 5050, 'fender': 500, 'jackson': 2000}
lst = guitars.keys()
print lst
lst.sort()
for key in lst:
    print key, guitars[key]
After executing the code we see that key elements of the dictionary are in alphabetical form.
['jackson', 'fender', 'gibson']
fender 500
gibson 5050
jackson 2000

Before entering the for loop we’ve printed out the list of keys in unsorted order that we’ve accomplished using keys method.

Nema komentara:

Objavi komentar