Access Dictionary Items in Python
You can access dictionary items in Python using the following methods:
(1) Using square brackets []
You can use the key inside square brackets []
to retrieve its corresponding value.
For example:
person = {"name": "James Bond", "age": 37, "city": "London"}
name = person["name"]
age = person["age"]
city = person["city"]
print(name)
print(age)
print(city)
Output:
James Bond
37
London
If the key doesn’t exist in the dictionary, it raises a KeyError
.
(2) Using get() method
The get()
method returns the value for a given key. If the key is not found, it returns the default value (None
if no default is provided) instead of raising KeyError
.
For example:
person = {"name": "James Bond", "age": 37, "city": "London"}
name = person.get("name")
age = person.get("age")
city = person.get("city")
occupation = person.get("occupation", "Not Found")
salary = person.get("salary")
print(name)
print(age)
print(city)
print(occupation)
print(salary)
Output:
James Bond
37
London
Not Found
None
(3) Accessing all keys
You can get a view object containing all keys in a dictionary using the key()
method. This view object can be iterated.
For example:
person = {"name": "James Bond", "age": 37, "city": "London"}
keys = person.keys()
print(keys)
for key in keys:
print(key)
Output:
dict_keys(['name', 'age', 'city'])
name
age
city
(4) Accessing all values
You can get a view object containing all the values using the values()
method.
For example:
person = {"name": "James Bond", "age": 37, "city": "London"}
values = person.values()
print(values)
for value in values:
print(value)
Output:
dict_values(['James Bond', 37, 'London'])
James Bond
37
London
(5) Accessing all key-value pairs (items)
The items()
method returns a view object containing all the key-value pairs as tuples. This is useful for iterating through the dictionary and accessing both keys and values.
For example:
person = {"name": "James Bond", "age": 37, "city": "London"}
items = person.items()
for key, value in items:
print(f"Key: {key} Value: {value}")
Output:
Key: name Value: James Bond
Key: age Value: 37
Key: city Value: London
(6) Check if a key exists
You can check if a key exist in a dictionary using the in
keyword.
For example:
person = {"name": "James Bond", "age": 37, "city": "London"}
if "age" in person.keys():
print("Age is present in the dictionary")
Output:
Age is present in the dictionary
Also Read:
Access Nested Dictionary Items in Python