Put a key name inside square brackets to read the matching item from a dictionary:
Example
Read the value stored under "model":
Output: complete Python program
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
Get Keys
Calling keys() gives you a view of every key in the dictionary, which reads like a list.
Example
Retrieve all the keys:
Output: complete Python program
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.keys()
print(x)
Example
The keys view stays current: add an item to the dictionary and it shows up there as well:
Output: complete Python program
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
Get Values
Calling values() works the same way, giving you a list-like view of every value in the dictionary.
Example
Retrieve all the values:
Output: complete Python program
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.values()
print(x)
Example
Change a value in the dictionary and the values view changes with it:
Output: complete Python program
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
Example
Add an item to the dictionary and its value appears in the values view too:
Output: complete Python program
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
Get Items
Calling items() returns a list-like view holding each dictionary item as a tuple.
Example
Retrieve all the key:value pairs:
Output: complete Python program
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.items()
print(x)
Example
Change a value in the dictionary and the items view changes with it:
Output: complete Python program
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
Check if Key Exists
The in keyword tells you whether a given key exists in a dictionary:
Example
Find out whether "model" is one of the keys:
Output: complete Python program
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
The get() Method
Square brackets are not your only choice for reading a value. The get() method returns the same result:
Example
Use get() to read the value stored under "model":
Output: complete Python program
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.get("model")
print(x)