Learn Python 3 - Dictionaries
Learn Python 3 - Dictionaries
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 my_dictionary = {"song": "Estranged",
dictionary. Values can be written by placing key within "artist": "Guns N' Roses"}
square brackets next to the dictionary and using the print(my_dictionary["song"])
assignment operator ( = ). If the key already exists, the
my_dictionary["song"] = "Paradise City"
old value will 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" .
ex_dict.values()
# ["anteater", "bumblebee", "cheetah"]
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"