Dictionary in Python, is a mutable, dynamic size collection datatype. Python Dictionary stores elements in key-value pairs, where elements are indexed by keys and each unique key maps to a specific value. Dictionary keys can only be of immutable datatype but values can be of any datatype. From Python version 3.7 and later, dictionaries maintain insertion order.
Access dictionary elements
Access any element in dictionary in efficient way is an important aspect and crucial for the performance of the program. Example of a Python dictionary:
# Example of a Python dictionary
employee = {
"employee_id": 1001,
"name": "Allen Smith",
"department": "Engineering",
"position": "Software Engineer",
"salary": 65000,
"skills": ["Python", "JavaScript", "SQL", "Machine Learning"],
"manager": { # nested dictionary
"name": "Bob Park",
"department": "Engineering"
},
"full_time": True
}
Lets understand the different scenarios using which we can access elements in dictionary.
Access element using key index
Dictionary elements are indexed by keys, this is similar to list where list elements were indexed by their positions. Dictionary allows only unique keys to be stored. Syntax for accessing elements using key index –
value = dictionary[key]
- If key exists in dictionary, then key index method will return the element value for the given key.
- if key does not exists in dictionary, then key index method will throw a
KeyError
.
# access element using key index
print("access element using key index")
shbytes = {"c1": "Python", "c2": "AWS", "c3": "Azure", "c4": "Java"}
print(shbytes)
print("value at key c2 - ", shbytes["c2"]) # access element using key index, c2 exists in dictionary
print("value at key c5 - ", shbytes["c5"]) # key c5 does not exists
In this program, we have defined a dictionary shbytes
. We are accessing an element using the index based on key shbytes["c2"]
. Value of element with c2
will be returned. Key c5
does not exists in dictionary. While accessing element shbytes["c5"]
will throw a KeyError.
Program Output
access element using key index
{'c1': 'Python', 'c2': 'AWS', 'c3': 'Azure', 'c4': 'Java'}
value at key c2 - AWS
Traceback (most recent call last):
File "D:\access-element-dictionary.py", line 7, in <module>
print("value at key c5 - ", shbytes["c5"])
~~~~~~~^^^^^^
KeyError: 'c5'
We got the value AWS
as an output, which is the value for key c2
. Key c5
does not exists, we got KeyError: c5
.
get()
method
Access element using Dictionary in Python provides a built-in method get()
to access the element value based on the key.
value = dictionary.get(key)
- If key exists in dictionary, then
get()
method will return the element value for the given key. - if key does not exists in dictionary, then
get()
will returnNone
. This is the difference between accessing element using key index method andget()
method. get()
method is mostly in scenarios where we don’t know if key exists in dictionary or not.
# access element using get method with key
print("access element using get method with key")
shbytes = {"c1": "Python", "c2": "AWS", "c3": "Azure", "c4": "Java"}
print(shbytes)
print("value at key c1 - ", shbytes.get("c1")) # access element using key index, c1 exists in dictionary
print("value at key c5 - ", shbytes.get("c5")) # key c5 does not exists
From the defined dictionary shbytes
, we are accessing an element using the get()
method shbytes.get("c1")
. Value of element with c1
will be returned. Key c5
does not exists in dictionary. While accessing element shbytes.get("c5")
will return None
.
Program Output
access element using get method with key
{'c1': 'Python', 'c2': 'AWS', 'c3': 'Azure', 'c4': 'Java'}
value at key c1 - Python
value at key c5 - None
We got the value Python
as an output, which is the value for key c1
. Key c5
does not exists, None
is returned for c5
.
keys()
, values()
and items()
Access Dictionary in Python provides a built-in methods keys()
, values()
and items()
to access all keys, values and items as list. These are called dictionary view objects.
keys_list = dictionary.keys()
=>keys()
method return all dictionary element keys as element of class type<class 'dict_keys'>
.values_list = dictionary.values()
=>values()
method return all dictionary element values as element of class type<class 'dict_values'>
.items_list = dictionary.items()
=>items()
method return all dictionary key-value pairs as tuple elements of class type<class 'dict_items'>
.key: value
pair is converted to(key, value)
tuple.
shbytes = {"c1": "Python", "c2": "AWS", "c3": "Azure", "c4": "Java"}
print(shbytes)
# get all keys of dictionary using key() method
print("get all keys of dictionary using key() method")
print("All keys in dictionary - ", shbytes.keys()) # using keys() method, return all keys as list
print(type(shbytes.keys()))
# get all values of dictionary using values() method
print("get all values of dictionary using values() method")
print("All values in dictionary - ", shbytes.values()) # using values() method, return all values as list
print(type(shbytes.values()))
# get all items of dictionary using items() method
print("get all items of dictionary using items() method")
print("All items in dictionary - ", shbytes.items()) # using items() method, return all key-value pairs as list
print(type(shbytes.items()))
In this program, we are using built-in methods keys()
, values()
and items()
on the defined dictionary shbytes
.
shbytes.keys()
will return all dictionary element keys as element of class type<class 'dict_keys'>
shbytes.values()
will return all dictionary element values as element of class type<class 'dict_values'>
shbytes.items()
will return all dictionary element key-value pairs as element of class type<class 'dict_items'>
Program Output
{'c1': 'Python', 'c2': 'AWS', 'c3': 'Azure', 'c4': 'Java'}
get all keys of dictionary using key() method
All keys in dictionary - dict_keys(['c1', 'c2', 'c3', 'c4'])
<class 'dict_keys'>
get all values of dictionary using values() method
All values in dictionary - dict_values(['Python', 'AWS', 'Azure', 'Java'])
<class 'dict_values'>
get all items of dictionary using items() method
All items in dictionary - dict_items([('c1', 'Python'), ('c2', 'AWS'), ('c3', 'Azure'), ('c4', 'Java')])
<class 'dict_items'>
In the program output, we got dictionary keys as dict_keys(['c1', 'c2', 'c3', 'c4'])
, dictionary values as dict_values(['Python', 'AWS', 'Azure', 'Java'])
and dictionary items as dict_items([('c1', 'Python'), ('c2', 'AWS'), ('c3', 'Azure'), ('c4', 'Java')])
.
Access nested dictionary elements
Dictionary can store any collection datatype as a value of the key. Using this we can store another dictionary as a value and can create nested dictionaries. Nested dictionary elements can be accessed using both dictionary[key]
and dictionary.get(key)
method.
# Nested dictionary
print("Access items in nested dictionary")
courses = {
"CS": {"topics": ["Algorithms", "Data Structures", "Programming Basics"]},
"MATH": {"topics": ["Integrals", "Series", "Differential Equations"]},
"ENG": {"topics": ["Poetry", "Prose", "Drama"]}
}
print(courses)
print("Math topics in dictionary - ", courses["MATH"]["topics"])
We have defined courses
as nested dictionary and accessing the nested element from that. Using courses["MATH"]["topics"]
, first we are accessing value of key MATH
, which is a dictionary. Then on that dictionary we are accessing value of key topics
, which is a list of topics.
Program Output
Access items in nested dictionary
{'CS': {'topics': ['Algorithms', 'Data Structures', 'Programming Basics']}, 'MATH': {'topics': ['Integrals', 'Series', 'Differential Equations']}, 'ENG': {'topics': ['Poetry', 'Prose', 'Drama']}}
Math topics in dictionary - ['Integrals', 'Series', 'Differential Equations']
List of topics ['Integrals', 'Series', 'Differential Equations']
is returned as an output for courses["MATH"]["topics"]
.
in
operator with dictionary
Using Using in
and not in
operator with dictionary, we can check if a particular key
exists in dictionary or not. This is useful, when we need to access values only for the existing keys.
# check for a key in dictionary
print("check for a key in dictionary")
shbytes = {"c1": "Python", "c2": "AWS", "c3": "Azure", "c4": "Java"}
print(shbytes)
if "c3" in shbytes:
print("c3 key is in the dictionary")
if "c5" not in shbytes:
print("c5 key is not in the dictionary")
Using in
operator, we are checking if key c3
exists in dictionary. Using not in
operator, we are checking if key c5
not exists in dictionary.
Program Output
check for a key in dictionary
{'c1': 'Python', 'c2': 'AWS', 'c3': 'Azure', 'c4': 'Java'}
c3 key is in the dictionary
c5 key is not in the dictionary
in
operator with keys()
, values()
, items()
method
Using Using in
operator combined with built-in keys()
, values()
, items()
methods, we can iterate over all the keys, values and items of the dictionary.
shbytes = {"c1": "Python", "c2": "Java"}
for key in shbytes.keys():
print(f"{key}",)
for value in shbytes.values():
print(f"{value} ")
for key, value in shbytes.items():
print(f"{key}: {value}")
We are iterating over all the keys, values and items of the dictionary and printing their values.
Program Output
c1
c2
Python
Java
c1: Python
c2: Java
Summary
In this article we learned about various scenarios to access elements in dictionary. We learned about:
Code – Github Repository
All code snippets and programs for this article and for Python tutorial, can be accessed from Github repository – Comments and Docstring in Python.
Python Topics
Interview Questions & Answers
Q: What happens when we access a key that doesn’t exist in a dictionary?
Python raises a KeyError
, when we access a key that doesn’t exist in a dictionary using dict[key]
. We can use following ways to handle this.
dict.get(key, default)
will returnNone
or the specifieddefault
value if the key is not found.try-except
block to catch theKeyError
and handle it appropriately.dict.setdefault(key, default)
will return the value if the key exists; if not, it will insert the key with the specified default value and return that.
Q: How can we access and modify deeply nested dictionary elements without raising an error if some keys are missing?
We can create a function to iterate through the keys, creating nested dictionary for subsequent keys.
def dictionary_deep_update(nested_dict, keys_list, value):
for key in keys_list[:-1]:
nested_dict = nested_dict.setdefault(key, {})
nested_dict[keys_list[-1]] = value
nested_dict = {}
dictionary_deep_update(nested_dict, ["a", "b", "c", "d"], 82)
print(nested_dict)
# nested_dict elements {'a': {'b': {'c': {'d': 82}}}}
In this example, dictionary_deep_update()
method safely navigates the dictionary and uses nested_dict.setdefault(key, {})
to create sub-dictionaries as necessary. Finally sets the desired value to final key. This approach prevents errors when intermediate keys do not exist.
Q: How to access multiple keys simultaneously from a dictionary?
There are two ways we can use to access multiple keys simultaneously from a dictionary.
- We can use a dictionary comprehension
- This approach gives more flexibility, as we can get the values as any data type structure like list, tuple or dictionary and we can perform any conditional checks on keys or values as well.
courses_dict = {"c1": "Python", "c2": "AWS", "c3": "Power BI", "c4": "Java"}
keys_list = ["c1", "c3"]
subset_dict = {key: courses_dict[key] for key in keys_list if key in courses_dict}
print(subset_dict)
# Elements in subset_dict => {'c1': 'Python', 'c3': 'Power BI'}
- We can use
itemgetter
function from theoperator
module => In this case, we get key values as tuple. - This approach is more efficient if we are accessing large number of keys simultaneously.
from operator import itemgetter
courses_dict = {"c1": "Python", "c2": "AWS", "c3": "Power BI", "c4": "Java"}
keys_list = ["c1", "c3"]
values_tuple = itemgetter(*keys_list)(courses_dict)
print(values_tuple)
# Elements in values_tuple => ('Python', 'Power BI')
map
or filter
functions?
Q: How to access and manipulate dictionary elements using map()
and filter()
functions are used on dictionary elements to perform transformations or filtering operations.
map()
is used to map key and value. This key and value can be modified during the applied lambda function.
numbers_dict = {"a": 11, "b": 22, "c": 33}
# Increment all values by 2
incremented_dict = dict(map(lambda item: (item[0], item[1] + 2), numbers_dict.items()))
print(incremented_dict)
# Elements in incremented_dict => {'a': 13, 'b': 24, 'c': 35}
filter()
to filter dictionary items based on a condition. Condition is applied using a lambda function.
numbers_dict = {"a": 11, "b": 22, "c": 33}
# Filter out items where the value is greater than 20
filtered_dict = dict(filter(lambda item: item[1] > 20, numbers_dict.items()))
print(filtered_dict)
# Elements in filtered_dict => {'b': 22, 'c': 33}