Python Dictionary Get Value – A Simple Illustrated Guide

Python Dictionary Get Value

Whether you are a beginner or a professional, dictionaries are an integral part of your programming journey, especially if you are coding in Python. Python dictionaries are all about key-value pairs which help you to perform your task.

There are restrictions on dictionary keys, but values have none. Literally, anything can be a value. As long as your key is an immutable data type, your key-value pairs can be any combination of types you want. You have complete control! The question here is: “How do we access these values?” Thus, in this article, you will learn about the various ways to access/extract values from a Python dictionary.

✨ Scenario 1: Getting Values For Specified Keys

Problem: Given a Python dictionary, how to extract the values from this dictionary?

Example:

device = {
  "brand": "Apple",
  "model": "iPhone 12 Pro",
  "price": 999.00,
  "released": 2020
}

# Some method to extract model-name and price, i.e. iPhone 11 and $ 999.0 

So without further delay, let us have a look at the numerous methods of accessing the values.

➥ Method 1: Using Square Bracket Notation []

device = {
  "brand": "Apple",
  "model": "iPhone 12 Pro",
  "price": 999.00,
  "released": 2020
}

model = device['model']
price = device['price']
print("Name: ",model,"\nPrice: $",price)

Output:

Name:  iPhone 12 Pro 
Price: $ 999.0 

➥ Method 2: Using get()

The get() method in Python helps you to retrieve the value for the specified key if key is present in a given dictionary.

Solution: Let’s have a look at the solution to visualize the usage of the get() method to extract values from a dictionary.

device = {
    "brand": "Apple",
    "model": "iPhone 12 Pro",
    "price": 999.00,
    "released": 2020
}

model = device.get('model')
price = device.get('price')
print("Name: ", model, "\nPrice: $", price)

Output:

Name: iPhone 12 Pro
Price: $ 999.0

✨ Scenario 2: Getting All Values From The Dictionary

Given Dictionary:

device = {
    "brand": "Apple",
    "model": "iPhone 12 Pro",
    "price": 999.00,
    "released": 2020
}

➥ Method 1: Using values()

The values() method in Python returns a view object consisting the list of all values present in the dictionary. Therefore, if you wish to list all the values present in the dictionary then use the values() method.

device = {
    "brand": "Apple",
    "model": "iPhone 12 Pro",
    "price": 999.00,
    "released": 2020
}
val = list(device.values())
print(val)

# To access model name and Price of product
print("Name: ", val[1], "\nPrice: $", val[2])

Output:

['Apple', 'iPhone 12 Pro', 999.0, 2020]
Name:  iPhone 12 Pro 
Price: $ 999.0

➥ Method 2: Using For Loop

Another way of extracting all the values is to iterate over each item in the dictionary and print them one by one as shown below:

device = {
    "brand": "Apple",
    "model": "iPhone 12 Pro",
    "price": 999.00,
    "released": 2020
}
for val in device:
    print(device[val])

Output:

Apple
iPhone 12 Pro
999.0
2020

✨ Scenario 3: Getting List Of Values For List Of Keys

You might want to use a list of keys of a dictionary to get a list of corresponding values.

Example:

my_dict = {'roll1': 'Jenny', 'roll2': 'Gwen', 'roll3': 'Ben'}
my_keys = ['roll3', 'roll1']

# Expected Output: ['Ben','Jenny']

Without wasting time on theory, let us quickly dive into the solutions.

➥ Method 1: Using A List Comprehension

List comprehension is a compact way of creating lists. The simple formula is [expression + context].

  • Expression: What to do with each list element?
  • Context: What elements to select? The context consists of an arbitrary number of for and if statements.

Please refer to this article for a deeper dive into list comprehensions.

Solution:

my_dict = {'roll1': 'Jenny', 'roll2': 'Gwen', 'roll3': 'Ben'}
my_keys = ['roll3', 'roll1']
print([my_dict[x] for x in my_keys])

Output:

['Ben', 'Jenny']

➥ Method 2: Using map() and get() Method

  • The map() function returns a map object that is an iterator that saves all mapped elements so that you can iterate over them. 

❖ Read more about map() method in this article:- Python map() — Finally Mastering the Python Map Function

Thus, you can easily map the key-value pairs using the map() method and extract the respective values using the get method as shown in the solution below.

my_dict = {'roll1': 'Jenny', 'roll2': 'Gwen', 'roll3': 'Ben'}
my_keys = ['roll3', 'roll1']
print(list(map(my_dict.get, my_keys)))

Output:

['Ben', 'Jenny']

✨ Scenario 4: Getting Values From a Nested Dictionary

Some of you might be wondering, what is a nested dictionary?

❖ In simple terms, a nested dictionary in Python is a dictionary containing other dictionaries. In other words, a nested dictionary is a collection of two or more dictionaries.

Example:

people = {
    'Alice': {
        'phone': '6589',
        'address': '90 Eastlake Court'
        },

    'John': {
        'phone': '5693',
        'address': '560 Hartford Drive'
        },

    'David': {
        'phone': '8965',
        'address': '96 SW 42nd'
        }
}

Now, this brings us to couple of questions. Let’s explore them one by one.

➥ How To Access Items Of a Particular Child Dictionary Within The Parent Nested Dictionary?

The solution to this question is quite simple! To access elements of a particular child dictionary within the parent dictionary, you have to use [] notation to specify the child dictionary and then another [] to specify the particular value within that dictionary.

Example: The following code demonstrates how to extract the contents of the sub-dictionary ‘John‘ present in the above example. There are two scenarios here:

  • Scenario 1: get all values at once
  • Scenario 2: get a particular value (e.g. Address)
people = {
    'Alice': {
        'phone': '6589',
        'address': '90 Eastlake Court'
        },

    'John': {
        'phone': '5693',
        'address': '560 Hartford Drive'
        },

    'David': {
        'phone': '8965',
        'address': '96 SW 42nd'
        }
}
# Scenario 1: get all values at once
for x in people['Alice'].values():
    print(x)

# Scenario 2: get a particular value
print("Alice's Address: ",people['Alice']['address'])

Output:

6589
90 Eastlake Court
Alice's Address:  90 Eastlake Court

➥ How to Extract Values of a Particular Value From A List of All Nested Values?

Problem: Extract all the phone numbers present in the people dictionary.

Solution: You can access a particular value corresponding to the same key in every sub-dictionary of the nested dictionary with the help of a for loop and the items() method and then extract the required value using the key within the [] notation.

people = {
    'Alice': {
        'phone': '6589',
        'address': '90 Eastlake Court'
        },

    'John': {
        'phone': '5693',
        'address': '560 Hartford Drive'
        },

    'David': {
        'phone': '8965',
        'address': '96 SW 42nd'
        }
}
for key,val in people.items():
    print(val['phone'])

Output:

6589
5693
8965

You can also use a simple list comprehension to store the required values within a list using the following piece of code:

print([val['phone'] for key,val in people.items()])

Conclusion

With that, we come to the end of this comprehensive tutorial on how to access the values of a dictionary. After completing this article, you might want to have a look at the following article: How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist?

Please stay tuned and subscribe for interesting contents in the future. Happy coding! ? 

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!