Open In App

Access a Dictionary Key Value Present Inside a List

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Using square brackets
  2. Using get() method
  3. 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)


Output

Mark Zuckerberg

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)


Output

Sundar Pichai

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads