筛选字典仅包含某些键? [英] Filter dict to contain only certain keys?

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

问题描述

我有一个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天全站免登陆