06/09/2021, 12:47
Cheatsheets / Learn Python 3
Dictionaries
Accessing and writing data in a Python dictionary
Values in a Python dictionary can be accessed
by placing the key within square brackets next to my_dictionary = {"song":
the dictionary. Values can be written by placing "Estranged", "artist": "Guns N'
key within square brackets next to the dictionary Roses"}
and using the assignment operator ( = ). If the print(my_dictionary["song"])
key already exists, the old value will be
my_dictionary["song"] = "Paradise
overwritten. Attempting to access a value with a
City"
key that does not exist will cause a KeyError .
To illustrate this review card, the second line of
the example code block shows the way to
access the value using the key "song" . The
third line of the code block overwrites the value
that corresponds to the key "song" .
Syntax of the Python dictionary
The syntax for a Python dictionary begins with
the left curly brace ( { ), ends with the right roaster = {"q1": "Ashley", "q2":
curly brace ( } ), and contains zero or more key "Dolly"}
: value items separated by commas ( , ). The
key is separated from the value by a colon
( : ).
Merging Dictionaries with the .update() Method in Python
Given two dictionaries that need to be
combined, Python makes this easy with the dict1 = {'color': 'blue', 'shape':
.update() function. 'circle'}
For dict1.update(dict2) , the key-value pairs of dict2 = {'color': 'red', 'number':
dict2 will be written into the dict1 dictionary. 42}
For keys in both dict1 and dict2 , the value in
dict1 will be overwritten by the corresponding
dict1.update(dict2)
value in dict2 .
# dict1 is now {'color': 'red',
'shape': 'circle', 'number': 42}
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-dictionaries/cheatsheet Page 1 of 3
06/09/2021, 12:47
Dictionary value types
Python allows the values in a dictionary to be
any type – string, integer, a list, another dictionary = {
dictionary, boolean, etc. However, keys must 1: 'hello',
always be an immutable data type, such as 'two': True,
strings, numbers, or tuples. '3': [1, 2, 3],
In the example code block, you can see that the 'Four': {'fun': 'addition'},
keys are strings or numbers (int or float). The
5.0: 5.5
values, on the other hand, are many varied data
}
types.
Python dictionaries
A python dictionary is an unordered collection of
items. It contains data as a set of key: value my_dictionary = {1: "L.A. Lakers",
pairs. 2: "Houston Rockets"}
Dictionary Key-Value Methods
When trying to look at the information in a
Python dictionary, there are multiple methods ex_dict = {"a": "anteater", "b":
that return objects that contain the dictionary "bumblebee", "c": "cheetah"}
keys and values.
ex_dict.keys()
● .keys() returns the keys through a
# dict_keys(["a","b","c"])
dict_keys object.
● .values() returns the values through a ex_dict.values()
dict_values object.
# dict_values(["anteater",
● .items() returns both the keys and "bumblebee", "cheetah"])
values through a dict_items object.
ex_dict.items()
# dict_items([("a","anteater"),
("b","bumblebee"),("c","cheetah")])
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-dictionaries/cheatsheet Page 2 of 3
06/09/2021, 12:47
get() Method for Dictionary
Python provides a .get() method to access a
dictionary value if it exists. This method takes # without default
the key as the first argument and an optional {"name": "Victor"}.get("name")
default value as the second argument, and it # returns "Victor"
returns the value for the specified key if key is
in the dictionary. If the second argument is not
{"name": "Victor"}.get("nickname")
specified and key is not found then None is
# returns None
returned.
# with default
{"name": "Victor"}.get("nickname",
"nickname is not a key")
# returns "nickname is not a key"
The .pop() Method for Dictionaries in Python
Python dictionaries can remove key-value pairs
with the .pop() method. The method takes a famous_museums = {'Washington':
key as an argument and removes it from the 'Smithsonian Institution', 'Paris':
dictionary. At the same time, it also returns the 'Le Louvre', 'Athens': 'The
value that it removes from the dictionary. Acropolis Museum'}
famous_museums.pop('Athens')
print(famous_museums) #
{'Washington': 'Smithsonian
Institution', 'Paris': 'Le Louvre'}
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-dictionaries/cheatsheet Page 3 of 3