Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Beginner's Python

Adding new key-value pairs Looping through a dictionary


You can store as many key-value pairs as you want in a You can loop through a dictionary in three ways: you can
dictionary, until your computer runs out of memory. To add a loop through all the key-value pairs, all the keys, or all the

Cheat Sheet - new key-value pair to an existing dictionary give the name of
the dictionary and the new key in square brackets, and set it
equal to the new value.
values.
Dictionaries keep track of the order in which key-value
pairs are added. If you want to process the information in a

Dictionaries
This also allows you to start with an empty dictionary and different order, you can sort the keys in your loop, using the
add key-value pairs as they become relevant. sorted() function.
Adding a key-value pair Looping through all key-value pairs
What are dictionaries? alien_0 = {'color': 'green', 'points': 5} # Store people's favorite languages.
fav_languages = {
Python's dictionaries allow you to connect pieces of alien_0['x'] = 0 'jen': 'python',
related information. Each piece of information in a alien_0['y'] = 25 'sarah': 'c',
dictionary is stored as a key-value pair. When you alien_0['speed'] = 1.5 'edward': 'ruby',
provide a key, Python returns the value associated 'phil': 'python',
Starting with an empty dictionary }
with that key. You can loop through all the key-value
alien_0 = {}
pairs, all the keys, or all the values. # Show each person's favorite language.
alien_0['color'] = 'green'
alien_0['points'] = 5 for name, language in fav_languages.items():
Defining a dictionary print(f"{name}: {language}")
Use curly braces to define a dictionary. Use colons to
connect keys and values, and use commas to separate
Modifying values Looping through all the keys
individual key-value pairs. You can modify the value associated with any key in a # Show everyone who's taken the survey.
dictionary. To do so give the name of the dictionary and the for name in fav_languages.keys():
Making a dictionary key in square brackets, then provide the new value for that print(name)
alien_0 = {'color': 'green', 'points': 5} key.
Looping through all the values
Modifying values in a dictionary
Accessing values alien_0 = {'color': 'green', 'points': 5}
# Show all the languages that have been chosen.
for language in fav_languages.values():
To access the value associated with an individual key give print(alien_0) print(language)
the name of the dictionary and then place the key in a set
of square brackets. If the key you provided is not in the # Change the alien's color and point value. Looping through all the keys in reverse order
dictionary, an error will occur. alien_0['color'] = 'yellow'
# Show each person's favorite language,
You can also use the get() method, which returns alien_0['points'] = 10
# in reverse order by the person's name.
None instead of an error if the key doesn't exist. You can print(alien_0)
for name in sorted(fav_languages.keys(),
also specify a default value to use if the key is not in the reverse=True):
dictionary. Removing key-value pairs language = fav_languages[name]
Getting the value associated with a key You can remove any key-value pair you want from a print(f"{name}: {language}")
dictionary. To do this use the del keyword and the dictionary
alien_0 = {'color': 'green', 'points': 5}
name, followed by the key in square brackets. This will Dictionary length
print(alien_0['color']) delete the key and its associated value. You can find the number of key-value pairs in a dictionary
print(alien_0['points']) Deleting a key-value pair using the len() function.
Getting the value with get() alien_0 = {'color': 'green', 'points': 5} Finding a dictionary's length
print(alien_0) num_responses = len(fav_languages)
alien_0 = {'color': 'green'}
del alien_0['points']
alien_color = alien_0.get('color')
alien_points = alien_0.get('points', 0)
print(alien_0)
Python Crash Course
alien_speed = alien_0.get('speed') A Hands-on, Project-Based
Visualizing dictionaries
print(alien_color) Introduction to Programming
Try running some of these examples on pythontutor.com,
print(alien_points) and then run one of your own programs that uses ehmatthes.github.io/pcc_3e
print(alien_speed) dictionaries.
Nesting - A list of dictionaries Nesting - Lists in a dictionary Dictionary Comprehensions
It's sometimes useful to store a number of dictionaries in a Storing a list inside a dictionary allows you to associate more A comprehension is a compact way of generating a
list; this is called nesting. than one value with each key. dictionary, similar to a list comprehension. To make a
dictionary comprehension, define an expression for the
Storing dictionaries in a list Storing lists in a dictionary
key-value pairs you want to make. Then write a for loop to
# Start with an empty list. # Store multiple languages for each person. generate the values that will feed into this expression.
users = [] fav_languages = { The zip() function matches each item in one list to each
'jen': ['python', 'ruby'], item in a second list. It can be used to make a dictionary
# Make a new user, and add them to the list. 'sarah': ['c'], from two lists.
new_user = { 'edward': ['ruby', 'go'],
'last': 'fermi', 'phil': ['python', 'haskell'], Using a loop to make a dictionary
'first': 'enrico', } squares = {}
'username': 'efermi', for x in range(5):
} # Show all responses for each person. squares[x] = x**2
users.append(new_user) for name, langs in fav_languages.items():
print(f"{name}: ") Using a dictionary comprehension
# Make another new user, and add them as well. for lang in langs:
squares = {x:x**2 for x in range(5)}
new_user = { print(f"- {lang}")
'last': 'curie', Using zip() to make a dictionary
'first': 'marie', Nesting - A dictionary of dictionaries
'username': 'mcurie', group_1 = ['kai', 'abe', 'ada', 'gus', 'zoe']
} You can store a dictionary inside another dictionary. In this group_2 = ['jen', 'eva', 'dan', 'isa', 'meg']
users.append(new_user) case each value associated with a key is itself a dictionary.
pairings = {name:name_2
Storing dictionaries in a dictionary for name, name_2 in zip(group_1, group_2)}
# Show all information about each user.
print("User summary:") users = {
for user_dict in users: 'aeinstein': { Generating a million dictionaries
for k, v in user_dict.items(): 'first': 'albert',
You can use a loop to generate a large number of
print(f"{k}: {v}") 'last': 'einstein',
'location': 'princeton', dictionaries efficiently, if all the dictionaries start out with
print("\n") similar data.
},
You can also define a list of dictionaries directly, A million aliens
without using append(): 'mcurie': {
'first': 'marie', aliens = []
# Define a list of users, where each user 'last': 'curie',
# is represented by a dictionary. 'location': 'paris', # Make a million green aliens, worth 5 points
users = [ }, # each. Have them all start in one row.
{ } for alien_num in range(1_000_000):
'last': 'fermi', new_alien = {
'first': 'enrico', for username, user_dict in users.items(): 'color': 'green',
'username': 'efermi', full_name = f"{user_dict['first']} " 'points': 5,
}, full_name += user_dict['last'] 'x': 20 * alien_num,
{ 'y': 0
'last': 'curie', location = user_dict['location'] }
'first': 'marie',
'username': 'mcurie', print(f"\nUsername: {username}") aliens.append(new_alien)
}, print(f"\tFull name: {full_name.title()}")
] print(f"\tLocation: {location.title()}") # Prove the list contains a million aliens.
num_aliens = len(aliens)
# Show all information about each user.
print("User summary:") Levels of nesting print("Number of aliens created:")
for user_dict in users: Nesting is extremely useful in certain situations. However, print(num_aliens)
for k, v in user_dict.items(): be aware of making your code overly complex. If you're
print(f"{k}: {v}") nesting items much deeper than what you see here there
print("\n") are probably simpler ways of managing your data, such as Weekly posts about all things Python
using classes. mostlypython.substack.com

You might also like