How to use list slicing In Python
This is a modified version of the first method, here instead of index for the value list, we pass the slicing range.
Syntax:
dictionary_name[key][start_index : end_index]
Example: using list slicing
Python3
# Creating dictionary which contains lists country = { "India" : [ "Delhi" , "Maharashtra" , "Haryana" , "Uttar Pradesh" , "Himachal Pradesh" ], "Japan" : [ "Hokkaido" , "Chubu" , "Tohoku" , "Shikoku" ], "United States" : [ "New York" , "Texas" , "Indiana" , "New Jersey" , "Hawaii" , "Alaska" ] } # extract the first 3 cities of India print (country[ "India" ][: 3 ]) # extract last 2 cities from Japan print (country[ "Japan" ][ - 2 :]) # extract all cities except last 3 cities from india print (country[ "India" ][: - 3 ]) # extract 2nd to 5th city from us print (country[ "United States" ][ 1 : 5 ]) |
Output :
[‘Delhi’, ‘Maharashtra’, ‘Haryana’]
[‘Tohoku’, ‘Shikoku’]
[‘Delhi’, ‘Maharashtra’]
[‘Texas’, ‘Indiana’, ‘New Jersey’, ‘Hawaii’]
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.