过滤字典以仅包含某些键? [英] Filter dict to contain only certain keys?

查看:31
本文介绍了过滤字典以仅包含某些键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 dict 有一大堆条目.我只对其中的几个感兴趣.有没有一种简单的方法来修剪所有其他的?

I've got a dict that has a whole bunch of entries. I'm only interested in a select few of them. Is there an easy way to prune all the other ones out?

推荐答案

构建一个新的字典:

dict_you_want = { your_key: old_dict[your_key] for your_key in your_keys }

使用字典理解.

如果您使用缺少它们的版本(即 Python 2.6 及更早版本),请将其设为 dict((your_key, old_dict[your_key]) for ...).这是一样的,虽然更丑.

If you use a version which lacks them (ie Python 2.6 and earlier), make it dict((your_key, old_dict[your_key]) for ...). It's the same, though uglier.

请注意,这与 jnnnnn 的版本不同,对于任何大小的 old_dict 都具有稳定的性能(仅取决于 your_keys 的数量).无论是速度还是内存.由于这是一个生成器表达式,它一次只处理一项,并且不会查看 old_dict 的所有项.

Note that this, unlike jnnnnn's version, has stable performance (depends only on number of your_keys) for old_dicts of any size. Both in terms of speed and memory. Since this is a generator expression, it processes one item at a time, and it doesn't looks through all items of old_dict.

就地删除所有内容:

unwanted = set(keys) - set(your_dict)
for unwanted_key in unwanted: del your_dict[unwanted_key]

这篇关于过滤字典以仅包含某些键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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