Access a Dictionary Key Value Present Inside a List
Last Updated :
12 Feb, 2024
The dictionary is a data structure in Python. A Dictionary in Python holds a key-value pair in it. Every key in the dictionary is unique. A value present in Dictionary can be accessed in Python in two different ways. A list can hold any data structure to it. A list can also contain a dictionary in it. In this article, we will see how to access a dictionary key value present inside a list in Python.
Access A Dictionary Key Value Present Inside a List
Below are some of the ways by which we can access a dictionary key value present inside a list in Python:
- Using square brackets
- Using get() method
- Using for loop
Access A Dictionary Key Using square brackets
In this example, a dictionary “companies” associates tech company names with their founders. The code then retrieves the founder of “Meta” from the list “myList” and prints the result, yielding “Mark Zuckerberg.”
Python3
companies = { "Microsoft" : "Bill Gates" , "Meta" : "Mark Zuckerberg" ,
"Tesla" : "Elon Musk" , "Google" : "Sundar Pichai" , "iPhone" : "Tim Cook" }
myList = [ "Hello" , companies, "12345" , 100 ]
answer = myList[ 1 ][ "Meta" ]
print (answer)
|
Access A Dictionary Key Using get() method
In this example, a dictionary “companies” associates tech company names with their founders. The code retrieves the founder of “Google” from the list “myList” using the `get` method and prints the result, yielding “Sundar Pichai” or `None` if the key is not found.
Python3
companies = { "Microsoft" : "Bill Gates" , "Meta" : "Mark Zuckerberg" ,
"Tesla" : "Elon Musk" , "Google" : "Sundar Pichai" , "iPhone" : "Tim Cook" }
myList = [ "Hello" , companies, "12345" , 100 ]
answer = myList[ 1 ].get( "Google" )
print (answer)
|
Access A Dictionary Key Using for loop
In this example, there’s a dictionary “student” with keys “name,” “age,” and “lastName.” The dictionary is then placed in a list called “sampleList.” The code iterates through the list, and for each dictionary in the list, it iterates through key-value pairs using the items()
method.
Python3
student = { "name" : "Alice" , "age" : 10 , "lastName" : "John" }
sampleList = [student]
for element in sampleList:
for studentKey, studentValue in element.items():
print (studentKey, "=" , studentValue)
|
Output
name = Alice
age = 10
lastName = John
Share your thoughts in the comments
Please Login to comment...