How to get multiple dictionary values?

PythonDictionary

Python Problem Overview


I have a dictionary in Python, and what I want to do is get some values from it as a list, but I don't know if this is supported by the implementation.

myDictionary.get('firstKey')   # works fine

myDictionary.get('firstKey','secondKey')
# gives me a KeyError -> OK, get is not defined for multiple keys
myDictionary['firstKey','secondKey']   # doesn't work either

Is there any way I can achieve this? In my example it looks easy, but let's say I have a dictionary of 20 entries, and I want to get 5 keys. Is there any other way than doing the following?

myDictionary.get('firstKey')
myDictionary.get('secondKey')
myDictionary.get('thirdKey')
myDictionary.get('fourthKey')
myDictionary.get('fifthKey')

Python Solutions


Solution 1 - Python

There already exists a function for this:

from operator import itemgetter

my_dict = {x: x**2 for x in range(10)}

itemgetter(1, 3, 2, 5)(my_dict)
#>>> (1, 9, 4, 25)

itemgetter will return a tuple if more than one argument is passed. To pass a list to itemgetter, use

itemgetter(*wanted_keys)(my_dict)

Keep in mind that itemgetter does not wrap its output in a tuple when only one key is requested, and does not support zero keys being requested.

Solution 2 - Python

Use a for loop:

keys = ['firstKey', 'secondKey', 'thirdKey']
for key in keys:
    myDictionary.get(key)

or a list comprehension:

[myDictionary.get(key) for key in keys]

Solution 3 - Python

I'd suggest the very useful map function, which allows a function to operate element-wise on a list:

mydictionary = {'a': 'apple', 'b': 'bear', 'c': 'castle'}
keys = ['b', 'c']

values = list( map(mydictionary.get, keys) )

# values = ['bear', 'castle']

Solution 4 - Python

You can use At from pydash:

from pydash import at
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_list = at(my_dict, 'a', 'b')
my_list == [1, 2]

Solution 5 - Python

As I see no similar answer here - it is worth pointing out that with the usage of a (list / generator) comprehension, you can unpack those multiple values and assign them to multiple variables in a single line of code:

first_val, second_val = (myDict.get(key) for key in [first_key, second_key])

Solution 6 - Python

If you have pandas installed you can turn it into a series with the keys as the index. So something like

import pandas as pd

s = pd.Series(my_dict)

s[['key1', 'key3', 'key2']]

Solution 7 - Python

I think list comprehension is one of the cleanest ways that doesn't need any additional imports:

>>> d={"foo": 1, "bar": 2, "baz": 3}
>>> a = [d.get(k) for k in ["foo", "bar", "baz"]]
>>> a
[1, 2, 3]

Or if you want the values as individual variables then use multiple-assignment:

>>> a,b,c = [d.get(k) for k in ["foo", "bar", "baz"]]
>>> a,b,c
(1, 2, 3)

Solution 8 - Python

def get_all_values(nested_dictionary):
    for key, value in nested_dictionary.items():
        if type(value) is dict:
            get_all_values(value)
        else:
            print(key, ":", value)

nested_dictionary = {'ResponseCode': 200, 'Data': {'256': {'StartDate': '2022-02-07', 'EndDate': '2022-02-27', 'IsStoreClose': False, 'StoreTypeMsg': 'Manual Processing Stopped', 'is_sync': False}}}

get_all_values(nested_dictionary)

Solution 9 - Python

TLDR: Use (dict1.get(key) for key in keys)


Use tuple (not list) comprehension because it is the fastest way. .get(key) and [key] have comparable speed, sometimes [key] is a little bit faster. If no key found in dict, .get(key) is safer (return None) than directly using indexing [key] (throw Error).

Benchmark:

from fakertype import FakerType
from faker import Faker

Faker.seed(42)
ft = FakerType()
dict1 = ft.fake_dict(n=100)
keys = list(dict1.keys())[:50]

%%timeit
[dict1[key] for key in keys]
# 14 µs ± 4.22 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%%timeit
itemgetter(*keys)(dict1)
# 2.8 µs ± 596 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%%timeit
(dict1.get(key) for key in keys)
# 585 ns ± 33 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%%timeit
(dict1[key] for key in keys)
# 590 ns ± 25.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Solution 10 - Python

If the fallback keys are not too many you can do something like this

value = my_dict.get('first_key') or my_dict.get('second_key')

Solution 11 - Python

def get_all_values(nested_dictionary):
    for key, val in nested_dictionary.items():
        data_list = []
        if type(val) is dict:
            for key1, val1 in val.items():
                data_list.append(val1)

    return data_list

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPKlumppView Question on Stackoverflow
Solution 1 - PythonVeedracView Answer on Stackoverflow
Solution 2 - PythonComputerFellowView Answer on Stackoverflow
Solution 3 - PythonscotttView Answer on Stackoverflow
Solution 4 - PythonbustawinView Answer on Stackoverflow
Solution 5 - PythonEpionView Answer on Stackoverflow
Solution 6 - PythonMosqueteiroView Answer on Stackoverflow
Solution 7 - PythonAndy BrownView Answer on Stackoverflow
Solution 8 - Python24_saurabh sharmaView Answer on Stackoverflow
Solution 9 - PythonMuhammad YasirroniView Answer on Stackoverflow
Solution 10 - PythonMuxView Answer on Stackoverflow
Solution 11 - Python24_saurabh sharmaView Answer on Stackoverflow