Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary get multiple values

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')
like image 459
PKlumpp Avatar asked Jun 13 '14 11:06

PKlumpp


People also ask

How can I get multiple values from a dictionary?

In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.

Can we add multiple values in dictionary Python?

By using the dictionary. update() function, we can easily append the multiple values in the existing dictionary. In Python, the dictionary. update() method will help the user to update the dictionary elements or if it is not present in the dictionary then it will insert the key-value pair.

How do you add multiple key-value pairs in a dictionary?

In Python, we can add multiple key-value pairs to an existing dictionary. This is achieved by using the update() method. This method takes an argument of type dict or any iterable that has the length of two - like ((key1, value1),) , and updates the dictionary with new key-value pairs.

How do you slice a dictionary in Python?

To slice a dictionary, you can use dictionary comprehension. In Python, dictionaries are a collection of key/value pairs separated by commas. When working with dictionaries, it can be useful to be able to easily access certain elements.


8 Answers

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.

like image 133
Veedrac Avatar answered Oct 12 '22 23:10

Veedrac


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]
like image 44
ComputerFellow Avatar answered Oct 12 '22 23:10

ComputerFellow


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']
like image 42
scottt Avatar answered Oct 12 '22 23:10

scottt


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]
like image 36
bustawin Avatar answered Oct 12 '22 23:10

bustawin


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])
like image 36
Epion Avatar answered Oct 13 '22 01:10

Epion


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']]
like image 33
Mosqueteiro Avatar answered Oct 13 '22 01:10

Mosqueteiro


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)
like image 37
Andy Brown Avatar answered Oct 13 '22 00:10

Andy Brown


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)
like image 32
24_saurabh sharma Avatar answered Oct 13 '22 00:10

24_saurabh sharma