Accessing List Values Within The Dictionary In Python

I am a self-taught Python developer who loves to write on Python Programming and quite obsessed with Machine Learning.
Search for a command to run...

I am a self-taught Python developer who loves to write on Python Programming and quite obsessed with Machine Learning.
No comments yet. Be the first to comment.
When you’re building an application, one thing you can’t skip is API testing. Whether it’s a login flow, payment gateway, or a complex e-commerce workflow, ensuring your APIs behave correctly saves you from nasty surprises in production. I had alread...

PyPy is an implementation of Python written in RPython (Reduced Python) language, and it is seen as a replacement for CPython. PyPy claims that it is almost a drop-in replacement for CPython and can beat it on speed and memory usage. It supports libr...

You must have used functions provided by the os module in Python several times in your projects. These could be used to create a file, walk down a directory, get info on the current directory, perform path operations, and more. In this article, we’ll...

FastAPI is a fast and modern web framework known for its support for asynchronous REST API and ease of use. In this article, we’ll see how to stream videos on frontend in FastAPI. StreamingResponse Stream Local Video FastAPI provides a StreamingRespo...

Have you ever come across circular imports in Python? Well, it’s a very common code smell that indicates something’s wrong with the design or structure. Circular Import Example How does circular import occur? This import error usually occurs when two...
The dictionary is a data structure in Python that belongs to the mapping category. When data(key-value) is enclosed by curly({ }) braces, we can say it is a dictionary.
A dictionary has a key that holds a value, also known as a key-value pair. Using the dictionary[key], we can get the value assigned to the key.
What if the dictionary contains the values in the form of a list? In this article, we'll look at all of the different ways to access items from lists within the dictionary.
Given data contains items in a list as the values of keys within the dictionary. We'll work with this given data throughout the article.

In the following example, we've used the indexing method and passed the index along with the key from which the value is to be extracted.
The convention dict_name[key][index] must be used to access the list values from the dictionary.
# Using indexing
# Accessing list items from the key
acc_key = my_data['Python dev']
print(acc_key)
# Accessing first list item from the key
acc_data = my_data['C++ dev'][0]
print(acc_data)
# Accessing third list item from the key
acc_data1 = my_data['PHP dev'][2]
print(acc_data1)
# Accessing second list item from the key 'name' from
# the dictionary 'detail' within the dictionary 'my_data'
acc_dict_item = my_data['detail']['name'][1]
print(acc_dict_item)
Output
['Sachin', 'Aman', 'Siya']
Rishu
Shalini
Siya
When we accessed only the key, we got the entire list, but when we specified the index number with the key, we got the specific values.
It's the same as the previous method, except instead of specifying the index value, we've used the slicing range.
# Using slicing method
# Accessing list items by skipping 2 steps
val = my_data['Python dev'][:3:2]
print(val)
# Accessing first list item from the end
val1 = my_data['C++ dev'][-1:]
print(val1)
# Accessing list items except the last item
val2 = my_data['PHP dev'][:-1]
print(val2)
Output
['Sachin', 'Siya']
['Rahul']
['Abhishek', 'Peter']
The for loop has been used in the following example to iterate over the values of the list in the dictionary my_data.
# Using for loop
# 1 - Accessing key and values from the dict 'my_data'
for key, value in my_data.items():
print(key, value)
print('-'*20)
# 2 - Iterating over list items from each key
for key, value in my_data.items():
for items in value:
print(f'{key} - {items}')
print('-'*20)
# 3 - Iterating list items from nested dictionary 'detail'
for key, value in my_data['detail'].items():
for items in value:
print(f'{key} - {items}')
print('-'*20)
# 4 - Accessing list item from individual key
for value in my_data['PHP dev']:
print(value)
We iterated both keys and values from the dictionary my_data in the first block of code, then the list items from each key in the second block, the list items from each key within the nested dictionary detail in the third block, and the list items of the specific key in the last block of code.
Output
Python dev ['Sachin', 'Aman', 'Siya']
C++ dev ['Rishu', 'Yashwant', 'Rahul']
PHP dev ['Abhishek', 'Peter', 'Shalini']
detail {'name': ['Sachin', 'Siya'], 'hobby': ['Coding', 'Reading']}
--------------------
Python dev - Sachin
Python dev - Aman
Python dev - Siya
C++ dev - Rishu
C++ dev - Yashwant
C++ dev - Rahul
PHP dev - Abhishek
PHP dev - Peter
PHP dev - Shalini
detail - name
detail - hobby
--------------------
name - Sachin
name - Siya
hobby - Coding
hobby - Reading
--------------------
Abhishek
Peter
Shalini
The list comprehension technique is used in the following example. It's the same method as before, but this time we've used the for loop within the list.
# Using list comprehension
# Accessing list item from the key 'Python dev'
lst_com = [item for item in my_data['Python dev']]
print(lst_com)
# Accessing list item from nested dictionary
lst_com1 = [item for item in my_data['detail']['name']]
print(lst_com1)
Output
['Sachin', 'Aman', 'Siya']
['Sachin', 'Siya']
You've probably used the asterisk(*) operator for multiplication, exponentiation, **kwargs, *args, and other things, but we're going to use it as an unpacking operator.
# Using unpacking operator
# Accessing values from every key
using_unpkg_op = [*my_data.values()]
print(using_unpkg_op)
print('-'*20)
print(using_unpkg_op[0])
print('-'*20)
# Accessing list items from the key 'Python dev'
using_unpkg_op = [*my_data.get('Python dev')]
# Accessing first item from the list
print(using_unpkg_op[0])
The expression *my_data.values() in the preceding code will return all the values of the keys in the dictionary my_data, and once the values are returned, we can specify the index number to access specific data.
The expression *my_data.get('Python dev') returns the values of the key Python dev, and through indexing, we can access the list item.
Output
[['Sachin', 'Aman', 'Siya'], ['Rishu', 'Yashwant', 'Rahul'], ['Abhishek', 'Peter', 'Shalini'], {'name': ['Sachin', 'Siya'], 'hobby': ['Coding', 'Reading']}]
--------------------
['Sachin', 'Aman', 'Siya']
--------------------
Sachin
In this article, we've seen the different methods to access list items within the dictionary. The dictionary we've operated on contains the keys with the values as a list and also a nested dictionary.
We've used five methods to access the list items from the dictionary which are as follows:
Indexing - Using the bracket notation([ ])
Slicing - Using the list slicing
Iterating - Using the for loop
List comprehension technique
Unpacking(*) operator
Well, this is it for the article, try to find some more methods to access list items within the dictionary.
🏆Other articles you might be interested in if you liked this one
âś…How list reverse() is different from the reversed() in Python?
âś…8 different ways to reverse the Python list.
âś…Python one-liners that will make your code more efficient.
âś…Understanding NumPy argmax function in Python.
âś…How to read multiple files simultaneously using the with statement in Python?
âś…Using asynchronous(async/await) programming in Python.
âś…Different ways to remove whitespaces in Python.
That's all for now
Keep Coding✌✌