Python字典:获取键列表的值。

时间:2021-11-30 00:19:43

Is there a built-in/quick way to use a list of keys to a dictionary to get a list of corresponding items?

是否有一个内置/快速的方法来使用一个键列表来获取对应项的列表?

For instance I have:

例如我有:

>>> mydict = {'one': 1, 'two': 2, 'three': 3}
>>> mykeys = ['three', 'one']

How can I use mykeys to get the corresponding values in the dictionary as a list?

如何使用mykeys在字典中获取对应的值作为列表?

>>> mydict.WHAT_GOES_HERE(mykeys)
[3, 1]

10 个解决方案

#1


117  

A list comprehension seems to be a good way to do this:

列表理解似乎是一个很好的方法:

>>> [mydict[x] for x in mykeys]
[3, 1]

#2


57  

A couple of other ways than list-comp:

还有一些其他的方法比list-comp:

  • Build list and throw exception if key not found: map(mydict.__getitem__, mykeys)
  • 创建列表并抛出异常,如果没有找到key: map(mydict)。__getitem__ mykey)
  • Build list with None if key not found: map(mydict.get, mykeys)
  • 构建列表,如果没有找到关键字:map(mydict)。得到,mykey)

Alternatively, using operator.itemgetter can return a tuple:

另外,使用操作符。itemgetter可以返回一个tuple:

from operator import itemgetter
myvalues = itemgetter(*mykeys)(mydict)
# use `list(...)` if list is required

#3


21  

A little speed comparison:

一个速度的比较:

Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Dec  7 2015, 14:10:42) [MSC v.1500 64 bit (AMD64)] on win32
In[1]: l = [0,1,2,3,2,3,1,2,0]
In[2]: m = {0:10, 1:11, 2:12, 3:13}
In[3]: %timeit [m[_] for _ in l]  # list comprehension
1000000 loops, best of 3: 762 ns per loop
In[4]: %timeit map(lambda _: m[_], l)  # using 'map'
1000000 loops, best of 3: 1.66 µs per loop
In[5]: %timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
1000000 loops, best of 3: 1.65 µs per loop
In[6]: %timeit map(m.__getitem__, l)
The slowest run took 4.01 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 853 ns per loop
In[7]: %timeit map(m.get, l)
1000000 loops, best of 3: 908 ns per loop
In[33]: from operator import itemgetter
In[34]: %timeit list(itemgetter(*l)(m))
The slowest run took 9.26 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 739 ns per loop

So list comprehension and itemgetter are the fastest ways to do this.

所以列表理解和itemgetter是最快的方法。

UPDATE: For large random lists and maps I had a bit different results:

更新:对于大的随机列表和地图,我有一些不同的结果:

Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Dec  7 2015, 14:10:42) [MSC v.1500 64 bit (AMD64)] on win32
In[2]: import numpy.random as nprnd
l = nprnd.randint(1000, size=10000)
m = dict([(_, nprnd.rand()) for _ in range(1000)])
from operator import itemgetter
import operator
f = operator.itemgetter(*l)
%timeit f(m)
%timeit list(itemgetter(*l)(m))
%timeit [m[_] for _ in l]  # list comprehension
%timeit map(m.__getitem__, l)
%timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
%timeit map(m.get, l)
%timeit map(lambda _: m[_], l)
1000 loops, best of 3: 1.14 ms per loop
1000 loops, best of 3: 1.68 ms per loop
100 loops, best of 3: 2 ms per loop
100 loops, best of 3: 2.05 ms per loop
100 loops, best of 3: 2.19 ms per loop
100 loops, best of 3: 2.53 ms per loop
100 loops, best of 3: 2.9 ms per loop

So in this case the clear winner is f = operator.itemgetter(*l); f(m), and clear outsider: map(lambda _: m[_], l).

在这种情况下,显然的赢家是f = operator.itemgetter(*l);f(m)和clear局外人:map(lambda _: m[_], l)。

#4


10  

Try This:

试试这个:

mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one','ten']
newList=[mydict[k] for k in mykeys if k in mydict]
print newList
[3, 1]

#5


5  

Here are three ways.

这里有三种方法。

Raising KeyError when key is not found:

在未找到密钥时,提高密钥错误:

result = [mapping[k] for k in iterable]

Default values for missing keys.

丢失键的默认值。

result = [mapping.get(k, default_value) for k in iterable]

Skipping missing keys.

不丢失的钥匙。

found_keys = mapping.keys() & iterable
result = [mapping[k] for k in iterable if k in found_keys]

#6


5  

Try this:

试试这个:

mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one'] # if there are many keys, use a set

[mydict[k] for k in mykeys]
=> [3, 1]

#7


3  

Or just mydict.keys() That's a builtin method call for dictionaries. Also explore mydict.values() and mydict.items().

或者仅仅是mydict.keys()这是对字典的构建方法调用。还可以探索mydict.values()和mydict.items()。

//Ah, OP post confused me.

//啊,OP post把我搞糊涂了。

#8


1  

Pandas does this very elegantly, though ofc list comprehensions will always be more technically Pythonic. I don't have time to put in a speed comparison right now (I'll come back later and put it in):

熊猫做这件事非常优雅,尽管ofc列表的理解将永远是技术上的python。我现在没有时间进行速度比较(稍后我会回来把它放进去):

import pandas as pd
mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one']
temp_df = pd.DataFrame().append(mydict)
# You can export DataFrames to a number of formats, using a list here. 
temp_df[mykeys].values[0]
# Returns: array([ 3.,  1.])

# If you want a dict then use this instead:
# temp_df[mykeys].to_dict(orient='records')[0]
# Returns: {'one': 1.0, 'three': 3.0}

#9


0  

Following closure of Python: efficient way to create a list from dict values with a given order

下面是Python的闭包:用给定的顺序创建一个从dict值创建列表的有效方法。

Retrieving the keys without building the list:

在不构建列表的情况下检索键:

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import collections


class DictListProxy(collections.Sequence):
    def __init__(self, klist, kdict, *args, **kwargs):
        super(DictListProxy, self).__init__(*args, **kwargs)
        self.klist = klist
        self.kdict = kdict

    def __len__(self):
        return len(self.klist)

    def __getitem__(self, key):
        return self.kdict[self.klist[key]]


myDict = {'age': 'value1', 'size': 'value2', 'weigth': 'value3'}
order_list = ['age', 'weigth', 'size']

dlp = DictListProxy(order_list, myDict)

print(','.join(dlp))
print()
print(dlp[1])

The output:

输出:

value1,value3,value2

value3

Which matches the order given by the list

哪个符合列表给出的顺序?

#10


-1  

reduce(lambda x,y: mydict.get(y) and x.append(mydict[y]) or x, mykeys,[])

incase there are keys not in dict.

如果有钥匙,就不会有命令。

#1


117  

A list comprehension seems to be a good way to do this:

列表理解似乎是一个很好的方法:

>>> [mydict[x] for x in mykeys]
[3, 1]

#2


57  

A couple of other ways than list-comp:

还有一些其他的方法比list-comp:

  • Build list and throw exception if key not found: map(mydict.__getitem__, mykeys)
  • 创建列表并抛出异常,如果没有找到key: map(mydict)。__getitem__ mykey)
  • Build list with None if key not found: map(mydict.get, mykeys)
  • 构建列表,如果没有找到关键字:map(mydict)。得到,mykey)

Alternatively, using operator.itemgetter can return a tuple:

另外,使用操作符。itemgetter可以返回一个tuple:

from operator import itemgetter
myvalues = itemgetter(*mykeys)(mydict)
# use `list(...)` if list is required

#3


21  

A little speed comparison:

一个速度的比较:

Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Dec  7 2015, 14:10:42) [MSC v.1500 64 bit (AMD64)] on win32
In[1]: l = [0,1,2,3,2,3,1,2,0]
In[2]: m = {0:10, 1:11, 2:12, 3:13}
In[3]: %timeit [m[_] for _ in l]  # list comprehension
1000000 loops, best of 3: 762 ns per loop
In[4]: %timeit map(lambda _: m[_], l)  # using 'map'
1000000 loops, best of 3: 1.66 µs per loop
In[5]: %timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
1000000 loops, best of 3: 1.65 µs per loop
In[6]: %timeit map(m.__getitem__, l)
The slowest run took 4.01 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 853 ns per loop
In[7]: %timeit map(m.get, l)
1000000 loops, best of 3: 908 ns per loop
In[33]: from operator import itemgetter
In[34]: %timeit list(itemgetter(*l)(m))
The slowest run took 9.26 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 739 ns per loop

So list comprehension and itemgetter are the fastest ways to do this.

所以列表理解和itemgetter是最快的方法。

UPDATE: For large random lists and maps I had a bit different results:

更新:对于大的随机列表和地图,我有一些不同的结果:

Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Dec  7 2015, 14:10:42) [MSC v.1500 64 bit (AMD64)] on win32
In[2]: import numpy.random as nprnd
l = nprnd.randint(1000, size=10000)
m = dict([(_, nprnd.rand()) for _ in range(1000)])
from operator import itemgetter
import operator
f = operator.itemgetter(*l)
%timeit f(m)
%timeit list(itemgetter(*l)(m))
%timeit [m[_] for _ in l]  # list comprehension
%timeit map(m.__getitem__, l)
%timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
%timeit map(m.get, l)
%timeit map(lambda _: m[_], l)
1000 loops, best of 3: 1.14 ms per loop
1000 loops, best of 3: 1.68 ms per loop
100 loops, best of 3: 2 ms per loop
100 loops, best of 3: 2.05 ms per loop
100 loops, best of 3: 2.19 ms per loop
100 loops, best of 3: 2.53 ms per loop
100 loops, best of 3: 2.9 ms per loop

So in this case the clear winner is f = operator.itemgetter(*l); f(m), and clear outsider: map(lambda _: m[_], l).

在这种情况下,显然的赢家是f = operator.itemgetter(*l);f(m)和clear局外人:map(lambda _: m[_], l)。

#4


10  

Try This:

试试这个:

mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one','ten']
newList=[mydict[k] for k in mykeys if k in mydict]
print newList
[3, 1]

#5


5  

Here are three ways.

这里有三种方法。

Raising KeyError when key is not found:

在未找到密钥时,提高密钥错误:

result = [mapping[k] for k in iterable]

Default values for missing keys.

丢失键的默认值。

result = [mapping.get(k, default_value) for k in iterable]

Skipping missing keys.

不丢失的钥匙。

found_keys = mapping.keys() & iterable
result = [mapping[k] for k in iterable if k in found_keys]

#6


5  

Try this:

试试这个:

mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one'] # if there are many keys, use a set

[mydict[k] for k in mykeys]
=> [3, 1]

#7


3  

Or just mydict.keys() That's a builtin method call for dictionaries. Also explore mydict.values() and mydict.items().

或者仅仅是mydict.keys()这是对字典的构建方法调用。还可以探索mydict.values()和mydict.items()。

//Ah, OP post confused me.

//啊,OP post把我搞糊涂了。

#8


1  

Pandas does this very elegantly, though ofc list comprehensions will always be more technically Pythonic. I don't have time to put in a speed comparison right now (I'll come back later and put it in):

熊猫做这件事非常优雅,尽管ofc列表的理解将永远是技术上的python。我现在没有时间进行速度比较(稍后我会回来把它放进去):

import pandas as pd
mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one']
temp_df = pd.DataFrame().append(mydict)
# You can export DataFrames to a number of formats, using a list here. 
temp_df[mykeys].values[0]
# Returns: array([ 3.,  1.])

# If you want a dict then use this instead:
# temp_df[mykeys].to_dict(orient='records')[0]
# Returns: {'one': 1.0, 'three': 3.0}

#9


0  

Following closure of Python: efficient way to create a list from dict values with a given order

下面是Python的闭包:用给定的顺序创建一个从dict值创建列表的有效方法。

Retrieving the keys without building the list:

在不构建列表的情况下检索键:

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import collections


class DictListProxy(collections.Sequence):
    def __init__(self, klist, kdict, *args, **kwargs):
        super(DictListProxy, self).__init__(*args, **kwargs)
        self.klist = klist
        self.kdict = kdict

    def __len__(self):
        return len(self.klist)

    def __getitem__(self, key):
        return self.kdict[self.klist[key]]


myDict = {'age': 'value1', 'size': 'value2', 'weigth': 'value3'}
order_list = ['age', 'weigth', 'size']

dlp = DictListProxy(order_list, myDict)

print(','.join(dlp))
print()
print(dlp[1])

The output:

输出:

value1,value3,value2

value3

Which matches the order given by the list

哪个符合列表给出的顺序?

#10


-1  

reduce(lambda x,y: mydict.get(y) and x.append(mydict[y]) or x, mykeys,[])

incase there are keys not in dict.

如果有钥匙,就不会有命令。