是否有一种内置/快速的方法来使用字典的键列表来获得对应项的列表?

例如,我有:

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

我如何使用mykeys在字典中作为列表获得相应的值?

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

当前回答

Pandas非常优雅地做到了这一点,尽管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}

其他回答

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

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

Pandas非常优雅地做到了这一点,尽管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}
reduce(lambda x,y: mydict.get(y) and x.append(mydict[y]) or x, mykeys,[])

以防字典里没有钥匙。

试试这个:

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]

试试这个:

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]