从字典中提取键值对的子集? [英] Extract subset of key-value pairs from dictionary?

查看:37
本文介绍了从字典中提取键值对的子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a big dictionary object that has several key value pairs (about 16), but I am only interested in 3 of them. What is the best way (shortest/efficient/most elegant) to achieve that?

我所知道的最好的是:

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

我相信还有比这更优雅的方式.

I am sure there is a more elegant way than this.

推荐答案

你可以试试:

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

... 或在 Python 3 Python 2.7 或更高版本中(感谢 Fábio Diniz 指出它也适用于 2.7):

... 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')}

更新:正如 Håvard S 指出的那样,我假设您知道密钥是将在字典中 - 参见 他的回答 如果你不能做出这个假设.或者,正如 timbo 在评论中指出的那样,如果您想要 bigdict 中缺少的密钥映射到 None,你可以这样做:

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

如果您使用的是 Python 3,并且您希望新字典中的键实际存在于原始字典中,您可以使用事实来查看对象来实现一些集合操作:>

If you're using Python 3, and you only want keys in the new dict that actually exist in the original one, you can use the fact to view objects implement some set operations:

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

这篇关于从字典中提取键值对的子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆