Skip to content

Learning Python: Day 15

Looping through a dictionary’s keys in a particular order

  • looping a dictionary returns the items in the same order they were inserted
  • sometimes you’ll want to loop through a dictionary in a different order
  • you can sort the keys as they’re returned in the for loop
  • you can use the sorted() function to get a copy of the keys in order

favorite_languages = {

…. ‘jen’: ‘python’,

….’sarah’: ‘c’,

….’edward’: ‘rust’,

….’phil’: ‘python’,

….}

for name in sorted(favorite_languages.keys()):

….print(f”{name.title()}, thank you for taking the poll.”)

  • wrapped sorted() function around the dictionary.keys() method which tells Python to get all the keys in the dictionary and sort them before starting the loop

Edward, thank you for taking the poll.

Jen, thank you for taking the poll.

Phil, thank you for taking the poll.

Sarah, thank you for taking the poll.

Looping through all values in a dictionary

  • values() method – return a sequence of values without any keys

favorite_languages = {

…. ‘jen’: ‘python’,

….’sarah’: ‘c’,

….’edward’: ‘rust’,

….’phil’: ‘python’,

….}

print(“the following languages have been mentioned:”)

for language in favorite_languages.values():

….print(language.title())

  • for statements pulls values from the dictionary and assigns it to the variable languegae

The following languages have been mentioned:

Python

C

Rust

Python

  • set – is a collection in which each item must be unique, can be used to see values without repetition

favorite_langueges = {

….–snip–

….}

print(“The following languages have been mentioned:”)

for language in set(favorite_langueages.values()):

….print(langueage.titile())

  • set() pulls unique languages in favorite_langueages.values())

The following languages have been mentioned:

Python

C

Rust

  • can build a set directly using braces and separating the elements with commas:

>>> languages = {‘python’, ‘rust’, ‘python’, ‘c’}

>>> languages

{‘rust’, ‘python’, ‘c’}

  • easy to mistake sets for dictionaries because they’re both wrapped in braces
  • when you see braces but no key-value pairs, you’re probably looking at a set
  • unlike lists and dictionaries, sets do not retain items in a specific order

Nesting

  • nesting – storing multiple dictionaries in a list or a list of items as a value in a dictionary, or a dictionary inside another dictionary
  • powerful feature

A list of dictionaries

  • alien_0 dictionary contains a variety of information about one alien
  • for a fleet of aliens, you can make a list of aliens in which each alien is a dictionary of information about that alien

aliens.py

alien_0 = {‘color’, ‘green’, ‘points’: 5}

alien_1 = {‘color’, ‘yellow’, ‘points’: 10}

alien_2 = {‘color’, ‘red’, ‘points’: 15}

aliens = [alien_0, alien_1, alien_2]

for alien in aliens:

….print(alien)

  • first, create three dictionaries, each representing a different alien
  • store each dictionary in a list called aliens
  • loop through the list and print out each alien

{‘color’, ‘green’, ‘points’: 5}

{‘color’, ‘yellow’, ‘points’: 10}

{‘color’, ‘red’, ‘points’: 15}

  • a more realistic example involves more than three aliens with code that automatically generates each alien
  • can use range() to create a fleet of 30 aliens:

# Make an empty list for storing aliens.

aliens = []

# Make 30 green aliens.

for alien_number in range(30):

….new_alien = {‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}

….aliens.append(new_alien)

#Show the first 5 aliens.

for alien in aliens[:5}:

….print(alien)

print(“…”)

# Show how many aliens have been created.

print(f”Total number of aliens: {len(aliens)}”)

  • example begins with an empty list
  • range() function returns a series of numbers, which tells Python how many times we want the loop to repeat, with each loop run, we create a new alien and then append each new alien to the list of aliens
  • use a slice to print the first five aliens, and finally, print the length of the list to prove we’ve actually generated the full fleet of 30 aliens

{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}

{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}

{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}

{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}

{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}

Total number of aliens: 30

  • aliens all have the same characteristics, but Python considers each one a separate object which allows us to modify each one individually

End of study session.

Tags:

Leave a Reply

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