Python – Accessing Items in Lists Within Dictionary
Given a dictionary with values as a list, the task is to write a python program that can access list value items within this dictionary.
Method 1: Manually accessing the items in the list
This is a straightforward method, where the key from which the values have to be extracted is passed along with the index for a specific value.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Example: direct indexing
[‘Delhi’, ‘Maharastra’, ‘Haryana’, ‘Uttar Pradesh’, ‘Himachal Pradesh’]
Method 2: Using Loop
The easiest way to achieve the task given is to iterate over the dictionary.
Example: Using loop
India : Delhi
India : Maharastra
India : Haryana
India : Uttar Pradesh
India : Himachal Pradesh
Japan : Hokkaido
Japan : Chubu
Japan : Tohoku
Japan : Shikoku
United States : New York
United States : Texas
United States : Indiana
United States : New Jersey
United States : Hawaii
United States : Alaska
Method 3: Accessing a particular list of the key
This is more or less the first two methods combined, where using the key the value list is iterated.
Example: Accessing a particular list of the key
Method 4: Using list slicing
This is a modified version of the first method, here instead of index for the value list, we pass the slicing range.
dictionary_name[key][start_index : end_index]
Example: using list slicing
[‘Delhi’, ‘Maharastra’, ‘Haryana’]
[‘Texas’, ‘Indiana’, ‘New Jersey’, ‘Hawaii’]