简体   繁体   English

在Python中通过键有效选择字典项

[英]Selecting dictionary items by key efficiently in Python

suppose I have a dictionary whose keys are strings. 假设我有一本字典,其键是字符串。 How can I efficiently make a new dictionary from that which contains only the keys present in some list? 如何从仅包含某个列表中存在的键的字典有效地制作一个新字典?

for example: 例如:

# a dictionary mapping strings to stuff
mydict = {'quux': ...,
          'bar': ...,
          'foo': ...}

# list of keys to be selected from mydict
keys_to_select = ['foo', 'bar', ...]

The way I came up with is: 我想出的方法是:

filtered_mydict = [mydict[k] for k in mydict.keys() \ 
                   if k in keys_to_select]

but I think this is highly inefficient because: (1) it requires enumerating the keys with keys(), (2) it requires looking up k in keys_to_select each time. 但是我认为这是非常低效的,因为:(1)它要求使用keys()枚举键,(2)它每次都需要在keys_to_select中查找k。 at least one of these can be avoided, I would think. 我认为,至少可以避免其中之一。 any ideas? 有任何想法吗? I can use scipy/numpy too if needed. 如果需要,我也可以使用scipy / numpy。

dict((k, mydict[k]) for k in keys_to_select)

if you know all the keys to select are also keys in mydict ; 如果您知道所有要选择的键也是mydict键; if that's not the case, 如果不是这样,

dict((k, mydict[k]) for k in keys_to_select if k in mydict)

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

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