Access Dictionary within List in Python (Example)
In this post, I’ll illustrate how to access a dictionary within a list in Python programming.
Table of contents:
So without further additions, let’s get started.
Example Data
First, we need to construct our example data, which is a list of two dictionaries where each dictionary has two key-value pairs, as shown below.
data = [{"five" : 5, "seven" : 7}, {"four" : 4, "six" : 6}] # constructing example list
Example: Access Dictionary within List in Python
Let’s solve the problem step by step. First, we need to access the elements of the list, which are the dictionaries in this case, by iterating through the list. For the output, see below.
for some_dict in range(len(data)): # iterating through the list print(data[some_dict]) # {'five': 5, 'seven': 7} # {'four': 4, 'six': 6}
To access the elements inside the dictionaries, we need to access the dictionary first, then use the keys of the dictionaries to reach their elements.
print(data[0]["five"], data[1]["six"]) # accessing inside the dictionaries # 5 6
In this case, two elements are printed: the first one is the element labeled with the key “five” in the first dictionary, and the second one is the element labeled with the key “six” in the second dictionary.
Video, Further Resources & Summary
In case you need further explanations on the Python programming syntax of this post, I recommend watching the following video on my YouTube channel. In the video instruction, I’m illustrating the Python code of this article.
The YouTube video will be added soon.
Furthermore, you could have a look at the related posts on www.statisticsglobe.com. You can find a selection of articles below:
- Sort List of datetime Objects in Python
- Convert List from Character String to Integer in Python
- Check if a String Exists in a List in Python
- Count Duplicates in List in Python
- All Python Programming Examples
In this tutorial, I have demonstrated how to use a dictionary within lists in Python programming. If you have further questions, don’t hesitate to let me know in the comments.
This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get more information about his professional background, a list of all his tutorials, as well as an overview of his other tasks on Statistics Globe.
Statistics Globe Newsletter