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

Learn Python 3_ Dictionaries Cheatsheet _ Codecademy

Uploaded by

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

Learn Python 3_ Dictionaries Cheatsheet _ Codecademy

Uploaded by

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

12/3/24, 3:18 PM Learn Python 3: Dictionaries Cheatsheet | Codecademy

Cheatsheets / Learn Python 3

Dictionaries

Accessing and writing data in a Python dictionary

Values in a Python dictionary can be accessed by placing my_dictionary = {"song": "Estranged",


the key within square brackets next to the dictionary.
"artist": "Guns N' Roses"}
Values can be written by placing key within square
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 roaster = {"q1": "Ashley", "q2": "Dolly"}
curly brace ( { ), ends with the right curly brace ( } ), 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 dict1 = {'color': 'blue', 'shape':
makes this easy with the .update() function.
'circle'}
For dict1.update(dict2) , the key-value pairs of dict2
will be written into the dict1 dictionary. dict2 = {'color': 'red', 'number': 42}
For keys in both dict1 and dict2 , the value in dict1
will be overwritten by the corresponding value in dict2 . dict1.update(dict2)

# dict1 is now {'color': 'red', 'shape':


'circle', 'number': 42}

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-dictionaries/cheatsheet 1/3
12/3/24, 3:18 PM Learn Python 3: Dictionaries Cheatsheet | Codecademy

Dictionary value types

Python allows the values in a dictionary to be any type – dictionary = {


string, integer, a list, another dictionary, boolean, etc.
1: 'hello',
However, keys must always be an immutable data type,
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 float). 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 my_dictionary = {1: "L.A. Lakers", 2:


contains data as a set of key: value pairs.
"Houston Rockets"}

Dictionary Key-Value Methods

When trying to look at the information in a Python ex_dict = {"a": "anteater", "b":
dictionary, there are multiple methods that return objects
"bumblebee", "c": "cheetah"}
that contain the dictionary keys and values.
.keys() returns the keys through a dict_keys
object. ex_dict.keys()
.values() returns the values through a
# dict_keys(["a","b","c"])
dict_values object.
.items() returns both the keys and values
through a dict_items object. ex_dict.values()
# dict_values(["anteater", "bumblebee",
"cheetah"])

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

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-dictionaries/cheatsheet 2/3
12/3/24, 3:18 PM Learn Python 3: Dictionaries Cheatsheet | Codecademy

get() Method for Dictionary

Python provides a .get() method to access a # without default


dictionary value if it exists. This method takes the key
{"name": "Victor"}.get("name")
as the first argument and an optional default value as the
second argument, and it returns the value for the # returns "Victor"
specified key if key is in the dictionary. If the second
argument is not specified and key is not found then {"name": "Victor"}.get("nickname")
None is returned.
# returns None

# 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 famous_museums = {'Washington':
.pop() method. The method takes a key as an argument
'Smithsonian Institution', 'Paris': 'Le
and removes it from the dictionary. At the same time, it
also returns the value that it removes from the dictionary. Louvre', 'Athens': 'The Acropolis Museum'}
famous_museums.pop('Athens')
print(famous_museums) # {'Washington':
'Smithsonian Institution', 'Paris': 'Le
Louvre'}

Print Share

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-dictionaries/cheatsheet 3/3

You might also like