0% found this document useful (0 votes)
63 views

Learn Python 3 - Dictionaries Cheatsheet - Codecademy

Dictionaries in Python allow storing and accessing data using keys and values. Values can be accessed or updated by specifying the key within square brackets. Keys must be immutable types like strings or numbers, while values can be any data type. The .update() method merges two dictionaries, overwriting common keys. The .keys(), .values(), and .items() methods return lists of the dictionary's keys, values, or (key, value) tuples respectively. The .get() method accesses a value using a key, returning None if the key is missing. The .pop() method removes an item by key and returns the removed value.

Uploaded by

Joe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views

Learn Python 3 - Dictionaries Cheatsheet - Codecademy

Dictionaries in Python allow storing and accessing data using keys and values. Values can be accessed or updated by specifying the key within square brackets. Keys must be immutable types like strings or numbers, while values can be any data type. The .update() method merges two dictionaries, overwriting common keys. The .keys(), .values(), and .items() methods return lists of the dictionary's keys, values, or (key, value) tuples respectively. The .get() method accesses a value using a key, returning None if the key is missing. The .pop() method removes an item by key and returns the removed value.

Uploaded by

Joe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

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 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" .

Syntax of the Python dictionary


The syntax for a Python dictionary begins with the left
curly brace ( { ), ends with the right curly brace ( } ), roaster = {"q1": "Ashley", "q2": "Dolly"}
and contains zero or more key : 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 .update() function. dict1 = {'color': 'blue', 'shape':
For dict1.update(dict2) , the key-value pairs of 'circle'}
dict2 = {'color': 'red', 'number': 42}
dict2 will be written into the dict1 dictionary.
For keys in both dict1 and dict2 , the value in
dict1.update(dict2)
dict1 will be overwritten by the corresponding value
in dict2 .
# dict1 is now {'color': 'red', 'shape':
'circle', 'number': 42}

/
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"}

Dictionary accession methods


When trying to look at the information in a Python
dictionary, there are multiple methods that access the ex_dict = {"a": "anteater", "b":
dictionary and return lists of its contents. "bumblebee", "c": "cheetah"}
.keys() returns the keys (the rst object in the key-
value pair), .values() returns the values (the second ex_dict.keys()
object in the key-value pair), and .items() returns # ["a","b","c"]
both the keys and the values as a tuple.
ex_dict.values()
# ["anteater", "bumblebee", "cheetah"]

ex_dict.items()
# [("a","anteater"),("b","bumblebee"),
("c","cheetah")]

get() Method for Dictionary


Python provides a .get() method to access a
# without default
dictionary value if it exists. This method takes the
{"name": "Victor"}.get("name")
key as the rst argument and an optional default value
# returns "Victor"
as the second argument, and it returns the value for the
speci ed key if key is in the dictionary. If the
{"name": "Victor"}.get("nickname")
second argument is not speci ed and key is not found
# returns None
then None is 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 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'}

You might also like