从Python字典对象中提取键值对的子集?

我有一个大的字典对象,有几个关键值对(约16),但我只对其中3个感兴趣。 实现这个目标的最佳方法是什么(最短/最有效/最优雅)?

我所知道的最好的是:

bigdict = {'a':1,'b':2,....,'z':26} subdict = {'l':bigdict['l'], 'm':bigdict['m'], 'n':bigdict['n']} 

我相信有比这更优雅的方式。 想法?

你可以尝试:

 dict((k, bigdict[k]) for k in ('l', 'm', 'n')) 

…或进入 Python 3 Python版本2.7或更高版本(感谢FábioDiniz指出它也能在2.7版本中工作)

 {k: bigdict[k] for k in ('l', 'm', 'n')} 

更新:正如H ?vard S所指出的那样,我假设你知道密钥将在字典中 – 如果你不能做出这个假设,请看他的答案 。 或者,正如timbo在评论中指出的那样,如果你想要一个在bigdict缺less的键映射到None ,你可以这样做:

 {k: bigdict.get(k, None) for k in ('l', 'm', 'n')} 

如果您使用的是Python 3,并且您想要新的字典中实际存在的键,您可以使用视图对象实现一些设置操作的事实:

 {k: bigdict[k] for k in bigdict.keys() & {'l', 'm', 'n'}} 

有点矮,至less:

 wanted_keys = ['l', 'm', 'n'] # The keys you want dict((k, bigdict[k]) for k in wanted_keys if k in bigdict) 
 interesting_keys = ('l', 'm', 'n') subdict = {x: bigdict[x] for x in interesting_keys if x in bigdict} 

这个答案使用类似于所选答案的词典理解,但是除了遗漏的项目之外不会有。

python2版本:

 {k:v for k, v in bigDict.iteritems() if k in ('l', 'm', 'n')} 

python 3版本:

 {k:v for k, v in bigDict.items() if k in ('l', 'm', 'n')} 

所有提到的方法的速度比较:

 Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Jan 29 2016, 14:26:21) [MSC v.1500 64 bit (AMD64)] on win32 In[2]: import numpy.random as nprnd keys = nprnd.randint(1000, size=10000) bigdict = dict([(_, nprnd.rand()) for _ in range(1000)]) %timeit {key:bigdict[key] for key in keys} %timeit dict((key, bigdict[key]) for key in keys) %timeit dict(map(lambda k: (k, bigdict[k]), keys)) %timeit dict(filter(lambda i:i[0] in keys, bigdict.items())) %timeit {key:value for key, value in bigdict.items() if key in keys} 100 loops, best of 3: 3.09 ms per loop 100 loops, best of 3: 3.72 ms per loop 100 loops, best of 3: 6.63 ms per loop 10 loops, best of 3: 20.3 ms per loop 100 loops, best of 3: 20.6 ms per loop 

正如预料的那样:字典理解是最好的select。

也许:

 subdict=dict([(x,bigdict[x]) for x in ['l', 'm', 'n']]) 

Python 3甚至支持以下内容:

 subdict={a:bigdict[a] for a in ['l','m','n']} 

请注意,您可以检查字典中是否存在如下所示:

 subdict=dict([(x,bigdict[x]) for x in ['l', 'm', 'n'] if x in bigdict]) 

RESP。 为python 3

 subdict={a:bigdict[a] for a in ['l','m','n'] if a in bigdict} 

你也可以使用地图(这是一个非常有用的function,无论如何去了解):

sd = dict(map(lambda k: (k, l.get(k, None)), l))

例:

large_dictionary = {'a1':123, 'a2':45, 'a3':344} list_of_keys = ['a1', 'a3'] small_dictionary = dict(map(lambda key: (key, large_dictionary.get(key, None)), list_of_keys))

PS。 我从以前的答案中借用了.get(key,None):)

好的,这是困扰了我几次,所以谢谢你Jayesh问。

上面的答案看起来像任何一个好的解决scheme,但如果你使用这遍遍你的代码,这是合理的包装的function恕我直言。 另外,这里有两种可能的用例:一种是关心所有关键字是否在原始字典中。 还有一个你不知道的地方 平等对待这将是很好的。

所以,对于我的两个价值,我build议写一个字典的子类,例如

 class my_dict(dict): def subdict(self, keywords, fragile=False): d = {} for k in keywords: try: d[k] = self[k] except KeyError: if fragile: raise return d 

现在你可以拿出一个子字典了

 orig_dict.subdict(keywords) 

用法示例:

 # ## our keywords are letters of the alphabet keywords = 'abcdefghijklmnopqrstuvwxyz' # ## our dictionary maps letters to their index d = my_dict([(k,i) for i,k in enumerate(keywords)]) print('Original dictionary:\n%r\n\n' % (d,)) # ## constructing a sub-dictionary with good keywords oddkeywords = keywords[::2] subd = d.subdict(oddkeywords) print('Dictionary from odd numbered keys:\n%r\n\n' % (subd,)) # ## constructing a sub-dictionary with mixture of good and bad keywords somebadkeywords = keywords[1::2] + 'A' try: subd2 = d.subdict(somebadkeywords) print("We shouldn't see this message") except KeyError: print("subd2 construction fails:") print("\toriginal dictionary doesn't contain some keys\n\n") # ## Trying again with fragile set to false try: subd3 = d.subdict(somebadkeywords, fragile=False) print('Dictionary constructed using some bad keys:\n%r\n\n' % (subd3,)) except KeyError: print("We shouldn't see this message") 

如果你运行上面的所有代码,你应该看到(类似于)下面的输出(抱歉的格式):

原始字典:
'a':0,'c':2,'b':1,'e':4,'d':3,'g':6,'f':5,'i':8' h':7,'k':10,'j':9,'m':12,'l':11,'o':14,'n':13,'q':16,'p' :15,'s':18,'r':17,'u':20,'t':19,'w':22,'v':21,'y':24,'x':23 ,'z':25}

从奇数键字典:
'''':0,'c':2,'e':4,'g':6,'i':8,'k':10,'m':12,'o':14' q':16,'s':18,'u':20,'w':22,'y':24}

subd2构造失败:
原始字典不包含一些密钥

使用一些错误键构造的字典:
'b':1,'d':3,'f':5,'h':7,'j':9,'l':11,'n':13,'p':15' r':17,'t':19,'v':21,'x':23,'z':25}

还有一个(我更喜欢Mark Longair的回答)

 di = {'a':1,'b':2,'c':3} req = ['a','c','w'] dict([i for i in di.iteritems() if i[0] in di and i[0] in req])