简体   繁体   English

如何获取多个字典值?

[英]How to get multiple dictionary 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.我在 Python 中有一本字典,我想做的是从中获取一些值作为列表,但我不知道实现是否支持这一点。

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.在我的示例中,它看起来很简单,但假设我有一个包含 20 个条目的字典,我想获得 5 个键。 Is there any other way than doing the following?除了执行以下操作还有其他方法吗?

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

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.如果传递了多个参数, itemgetter将返回一个元组。 To pass a list to itemgetter , use要将列表传递给itemgetter ,请使用

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.请记住,当仅请求一个键时itemgetter不会将其输出包装在元组中,并且不支持请求零键。

Use a for loop:使用for循环:

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

or a list comprehension:或列表理解:

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

I'd suggest the very useful map function, which allows a function to operate element-wise on a list:我建议使用非常有用的map函数,它允许函数在列表上按元素操作:

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

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

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

You can use At from pydash :您可以使用来自 pydash 的 At At

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

正如我在这里没有看到类似的答案 - 值得指出的是,通过使用(列表/生成器)理解,您可以解压缩这些多个值并将它们分配给一行代码中的多个变量:

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

If you have pandas installed you can turn it into a series with the keys as the index.如果你安装了pandas ,你可以把它变成一个以键为索引的系列。 So something like所以像

import pandas as pd

s = pd.Series(my_dict)

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

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)

%timeit response of all the answers listed above. %timeit上面列出的所有答案的响应。 My apologies if missed some of the solutions, and I used my judgment to club similar answers.如果错过了一些解决方案,我深表歉意,我根据自己的判断来总结类似的答案。 itemgetter seems to be the winner to me. itemgetter似乎是我的赢家。 pydash reports much lesser time but I don't know why it ran lesser loops and don't know if I can call it a fastest. pydash报告的时间要少得多,但我不知道为什么它运行的循环更少,也不知道我是否可以称之为最快。 Your thoughts?你的想法?

from operator import itemgetter

my_dict = {x: x**2 for x in range(10)}
req_keys = [1, 3, 2, 5]
%timeit itemgetter(1, 3, 2, 5)(my_dict)
257 ns ± 4.61 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit [my_dict.get(key) for key in req_keys]
604 ns ± 6.94 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)


%timeit list( map(my_dict.get, req_keys) )
529 ns ± 34.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)


!pip install pydash
from pydash import at

%timeit at(my_dict, 1, 3, 2, 5)
22.2 µs ± 572 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)


%timeit (my_dict.get(key) for key in req_keys)
308 ns ± 6.53 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

s = pd.Series(my_dict)

%timeit s[req_keys]
334 µs ± 58.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
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)

Use list comprehension and create a function: 使用列表理解并创建一个函数:

def myDict(**kwargs):
  # add all of your keys here
  keys = ['firstKey','secondKey','thirdKey','fourthKey']

  # iterate through keys 
  # return the key element if it's in kwargs 
  list_comp = ''.join([val for val in keys if val in kwargs ])
  results = kwargs.get(list_comp,None)

  print(results)      

If you want to retain the mapping of the values to the keys, you should use a dict comprehension instead:如果要保留值到键的映射,则应改用 dict 理解:

{key: myDictionary[key] for key in [
  'firstKey',
  'secondKey',
  'thirdKey',
  'fourthKey',
  'fifthKey'
]}

Slighlty different variation of list comprehension approach.列表理解方法的细微差别。

#doc
[dict[key] for key in (tuple_of_searched_keys)]

#example
my_dict = {x: x**2 for x in range(10)}
print([my_dict[key] for key in (8,9)])

如果后备键不是太多,你可以做这样的事情

value = my_dict.get('first_key') or my_dict.get('second_key')
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM