从python字典对象中提取键值对的子集的最佳方式 [英] best way to extract subset of key-value pairs from python dictionary object
问题描述
我知道的最好的是:
bigdict = {'a':1,'b':2,....,'z':26}
subdict = {'l':bigdict [ 'l'],'m':bigdict ['m'],'n':bigdict ['n']}
我相信有比这更优雅的方式。想法?
您可以尝试:
('l','m','n')中的code> dict((k,bigdict [k]))
...或在 Python 3 Python 2.7或更高版本(感谢FábioDiniz ,指出它的工作在2.7):
{k:bigdict [k] for('l','m','n')}
更新:由于HåvardS 指出,我假设你知道密钥将在字典中 - 请参阅他的答案,如果你不能做出这样的假设。或者,如 timbo 在评论中指出的,如果您想要在 bigdict
映射到无
,您可以执行以下操作:
对于('l','m','n')中的k, {k:bigdict.get(k,None)}}
如果您使用的是Python 3,而您只需要 ,则需要在原来的实际存在的新dict中使用键,则可以使用事实上,视图对象实现了一些设置操作:
{k:bigdict [k] for k in bigdict.keys()& {'l','m','n'}}
I have a big dictionary object that has several key value pairs (about 16), I am only interested in 3 of them. What is the best way (shortest/efficient/elegant) to achieve that?
The best I know is:
bigdict = {'a':1,'b':2,....,'z':26}
subdict = {'l':bigdict['l'], 'm':bigdict['m'], 'n':bigdict['n']}
I am sure there is more elegant way than this. Ideas?
You could try:
dict((k, bigdict[k]) for k in ('l', 'm', 'n'))
... or in Python 3 Python versions 2.7 or later (thanks to Fábio Diniz for pointing that out that it works in 2.7 too):
{k: bigdict[k] for k in ('l', 'm', 'n')}
Update: As Håvard S points out, I'm assuming that you know the keys are going to be in the dictionary - see his answer if you aren't able to make that assumption. Alternatively, as timbo points out in the comments, if you want a key that's missing in bigdict
to map to None
, you can do:
{k: bigdict.get(k, None) for k in ('l', 'm', 'n')}
If you're using Python 3, and you only want want keys in the new dict that actually exist in the original one, you can use the fact the view objects implement some set operations:
{k: bigdict[k] for k in bigdict.keys() & {'l', 'm', 'n'}}
这篇关于从python字典对象中提取键值对的子集的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!