Method 5 : Using for loop and f-string
In this approach, we will use the for loop with the f-strings to fetch the values from the dictionary. It is a little modification of the method where the normal for loop has been used.
Step – 1 : Firstly we will iterate over the dictionary using two variables, one to point at the key and one to the values. We will also use the .items() method inside the for loop.
Step – 2: Next, as the dictionary consists of values which are of type lists so there must be more than one item in the list which we have to fetch and print. This is why we will again iterate over the second variable we took earlier to fetch each element of that particular key and print it.
Step – 3 : After printing all the elements of a certain key we will print something to separate it with the others like a line of dash(-) or dots(.).
Python3
# Python program to fetch # items from a list which acts # as a value of dictionary # defining the dictionary country = { "India" : [ "Delhi" , "Maharashtra" , "Haryana" , "Uttar Pradesh" , "Himachal Pradesh" ], "Japan" : [ "Hokkaido" , "Chubu" , "Tohoku" , "Shikoku" ], "United States" : [ "New York" , "Texas" , "Indiana" , "New Jersey" , "Hawaii" , "Alaska" ] } # Running the for loop to # iterate over the dictionary items # key -> key of the dictionary # val -> list of elements which acts as values of the dictionary for key, val in country.items(): # iterating over each of the list # to fetch all items and print it for i in val: # Using f-string here to print # the key with each element of a list key print (f "{key} : {i}" ) # This acts as a separator print ( "--------------------" ) |
India : Delhi India : Maharashtra 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 --------------------
Time Complexity – O(n**2) # using two for loops
Space Complexity – O(1) # No extra space has been used.
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.