Python Fundamentals_ Python Dictionaries
Python Fundamentals_ Python Dictionaries
Python Dictionaries
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 ( : ).
Given two dictionaries that need to be combined, dict1 = {'color': 'blue', 'shape':
Python 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
dict1.update(dict2)
dict2 .
https://www.codecademy.com/learn/dscp-python-fundamentals/modules/dscp-python-dictionaries/cheatsheet 1/3
9/1/24, 12:04 PM Python Fundamentals: Python Dictionaries Cheatsheet | Codecademy
Python dictionaries
When trying to look at the information in a Python ex_dict = {"a": "anteater", "b":
dictionary, there are multiple methods that return
"bumblebee", "c": "cheetah"}
objects 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/dscp-python-fundamentals/modules/dscp-python-dictionaries/cheatsheet 2/3
9/1/24, 12:04 PM Python Fundamentals: Python Dictionaries Cheatsheet | Codecademy
# with default
{"name": "Victor"}.get("nickname",
"nickname is not a key")
# returns "nickname is not a key"
Print Share
https://www.codecademy.com/learn/dscp-python-fundamentals/modules/dscp-python-dictionaries/cheatsheet 3/3