Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Dictionary Get Value – A Simple Illustrated Guide

#1
Python Dictionary Get Value – A Simple Illustrated Guide

Python Dictionary Get Valuehttps://blog.finxter.com/wp-content/uplo...00x300.jpg 300w, https://blog.finxter.com/wp-content/uplo...50x150.jpg 150w, https://blog.finxter.com/wp-content/uplo...68x768.jpg 768w" sizes="(max-width: 312px) 100vw, 312px" />

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 1: 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(val)

Output:

for val in device:
print(val)

✨ Scenario 2: 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 3: 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!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become 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.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

The post Python Dictionary Get Value – A Simple Illustrated Guide first appeared on Finxter.



https://www.sickgaming.net/blog/2021/03/...ted-guide/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python iter() — A Simple Illustrated Guide with Video xSicKxBot 0 38 03-08-2021, 12:28 AM
Last Post: xSicKxBot
  [Tut] Python repr() Function — A Helpful Guide with Example xSicKxBot 0 67 02-15-2021, 02:40 PM
Last Post: xSicKxBot
  [Tut] Python round() — A Simple Guide with Video xSicKxBot 0 57 02-13-2021, 12:41 PM
Last Post: xSicKxBot
  [Tut] Python help() xSicKxBot 0 65 01-22-2021, 01:02 AM
Last Post: xSicKxBot
  [Tut] A Guide to Python’s pow() Function xSicKxBot 0 82 12-22-2020, 02:24 PM
Last Post: xSicKxBot
  [Tut] Python complex() — A Useless Python Feature? xSicKxBot 0 73 12-19-2020, 02:05 AM
Last Post: xSicKxBot
  [Tut] Python range() Function — A Helpful Illustrated Guide xSicKxBot 0 69 12-13-2020, 01:22 AM
Last Post: xSicKxBot
  [Tut] Pandas apply() — A Helpful Illustrated Guide xSicKxBot 0 81 12-12-2020, 12:42 PM
Last Post: xSicKxBot
  [Tut] How to Reverse/Invert a Dictionary Mapping xSicKxBot 0 60 12-11-2020, 05:13 AM
Last Post: xSicKxBot
  [Tut] Matplotlib Scatter Plot – Simple Illustrated Guide xSicKxBot 0 70 11-25-2020, 01:23 AM
Last Post: xSicKxBot

Forum Jump:

[-]
Active Threads
[Tut] Private and Public Attributes in P...
Last Post: xSicKxBot
Yesterday 11:05 PM
» Replies: 0
» Views: 3
(Indie Deal) Adventure Tales Bundle, Qua...
Last Post: xSicKxBot
Yesterday 11:05 PM
» Replies: 0
» Views: 4
Mobile - Arena battler Smash Legends goe...
Last Post: xSicKxBot
Yesterday 11:05 PM
» Replies: 0
» Views: 3
News - Epic Secures $1 Billion In Fundin...
Last Post: xSicKxBot
Yesterday 11:04 PM
» Replies: 0
» Views: 3
News - Anniversary: The Animal Crossing ...
Last Post: xSicKxBot
Yesterday 11:04 PM
» Replies: 0
» Views: 3
News - TMNT: Shredder's Revenge Confirme...
Last Post: xSicKxBot
Yesterday 11:04 PM
» Replies: 0
» Views: 5
Unigine 2.14 Released
Last Post: xSicKxBot
Yesterday 03:06 PM
» Replies: 0
» Views: 8
News - Lawson Will Offer New Pokémon Sna...
Last Post: xSicKxBot
Yesterday 03:06 PM
» Replies: 0
» Views: 7
News - Nacon Announces WRC 10, Speeds On...
Last Post: xSicKxBot
Yesterday 03:06 PM
» Replies: 0
» Views: 5
News - Blizzard Arcade Collection Gets T...
Last Post: xSicKxBot
Yesterday 03:06 PM
» Replies: 0
» Views: 15

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020