Learn Python 3 - Dictionaries Cheatsheet - Codecademy
Learn Python 3 - Dictionaries Cheatsheet - Codecademy
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 the dictionary. my_dictionary = {"song": "Estranged",
Values can be written by placing key within square "artist": "Guns N' Roses"}
brackets next to the dictionary and using the assignment print(my_dictionary["song"])
operator ( = ). If the key already exists, the old value will my_dictionary["song"] = "Paradise City"
be overwritten. Attempting to access a value with a 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" .
/
Dictionary value types
Python allows the values in a dictionary to be any type –
string, integer, a list, another dictionary, boolean, etc. dictionary = {
However, keys must always be an immutable data type, 1: 'hello',
such as strings, numbers, or tuples. 'two': True,
In the example code block, you can see that the keys are
'3': [1, 2, 3],
strings or numbers (int or oat). The values, on the other
'Four': {'fun': 'addition'},
hand, are many varied data types.
5.0: 5.5
}
Python dictionaries
A python dictionary is an unordered collection of items. It
contains data as a set of key: value pairs. my_dictionary = {1: "L.A. Lakers", 2:
"Houston Rockets"}
ex_dict.items()
# [("a","anteater"),("b","bumblebee"),
("c","cheetah")]
# 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 key as an famous_museums = {'Washington':
argument and removes it from the dictionary. At the same 'Smithsonian Institution', 'Paris': 'Le
time, it also returns the value that it removes from the Louvre', 'Athens': 'The Acropolis Museum'}
dictionary. famous_museums.pop('Athens')
print(famous_museums) # {'Washington':
'Smithsonian Institution', 'Paris': 'Le
Louvre'}