Skip to content

Learning Python: Day 14

Looping through all the keys in a dictionary

  • keys() method – useful when you don’t need to work with all of the values in a dictionary

favorite_langueages = {

….’jen’: ‘python’,

….’sarah’: ‘c’,

….’edward’: ‘rust’,

….’phil’: ‘python’,

….}

for name in favorite_languages.keys():

….print(name.title())

  • for loop tellys Python to pull all keys from the dictionary favorite_langueages and assign them one at a time to the variable name

Jen

Sarah

Edward

Phil

  • looping through the keys is the default behavior when looping through a dictionary, so this code would be the same if you wrote

for name in favorite_languages:

  • rather than

for name in favorite_languages.keys():

  • you can choose to use the keys () method explicitly if it makes your code easier to read
  • can access the value associated with any key you care about inside the loop by using the current key

favorite_languages = {

….–snip–

….}

friends = [‘phil’, ‘sarah’]

for name in favorite_languages.keys():

….print(f”Hi {name.title()}.”)

if name in friends:

….language = favorite_languages[name].title()

….print(f”\t{name.title()}, I see you love {language}!”)

  • everyone’s name is printed, but our friends receive a special message:

Hi Jen.

Hi Sarah.

….Sarah, I see you love C!

Hi Edward.

Hi Phil.

….Phil, I see you love Python!

  • can also use keys() method to find out if a particular person was polled

favorite_languages = {

….–snip–

….}

if ‘erin’ not in favorite_languages.keys():

….print(“Erin, please take our poll!”)

  • the keys() method isn’t just for looping, it actually returns a sequence of all the keys, and the if statement simply checks if ‘erin’ is in this sequence

Erin, please take our poll!

End of study session.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *