Python Looping through a dictionary

Python Looping through a dictionary

Looping through a dictionary

You can loop through a dictionary in three ways: you can loop through all the key-value pairs, all the keys, or all the values.
A dictionary only tracks the connections between keys and values; it doesn't track the qrder of items in the dictionary. If you want to process the information in order, you can sort the keys in your loop.

#Looping through all key-value pairs

#store people's favorite languages.
fav_languages = {
 'jen': 'python',
 'sarah': 'c',
 'phil': 'python',

#show each person's favorite language.
for name, language in fav_languages.items():
 print(name + ":" + language)
#looping through all the keys
#show everyone who's taken the survey.
for name in fav_languages.keys():
#Looping through all the values
#show all the languagethat have been chose.
for language in fav_languages.values():
#Looping through all the keys in order
# show each person's favorite language,
# in order by the person's name.
for name in sorted (fav_languages.keys()):
 print(name + ":" + language)


looping dictionary


Dictionary Length 

you can find the number of key-value pairs in a dictionary.
#Finding a dictionary's length
num_responses = len(fav_languages)


Post a Comment