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

例如,我有:

>>> 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}

其他回答

这里有三种方法。

当找不到key时引发KeyError:

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

缺少键的默认值。

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

跳过丢失的键。

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

试试这个:

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]
new_dict = {x: v for x, v in mydict.items() if x in mykeys}

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,[])

以防字典里没有钥匙。