我有一个字典,里面有一大堆词条。我只对其中的几个感兴趣。有什么简单的方法可以把其他的都剪掉吗?
当前回答
你可以用我的函数库中的项目函数来做:
from funcy import project
small_dict = project(big_dict, keys)
还要看一下select_keys。
其他回答
这是我的方法,支持嵌套字段,如mongo查询。
使用方法:
>>> obj = { "a":1, "b":{"c":2,"d":3}}
>>> only(obj,["a","b.c"])
{'a': 1, 'b': {'c': 2}}
只有函数:
def only(object,keys):
obj = {}
for path in keys:
paths = path.split(".")
rec=''
origin = object
target = obj
for key in paths:
rec += key
if key in target:
target = target[key]
origin = origin[key]
rec += '.'
continue
if key in origin:
if rec == path:
target[key] = origin[key]
else:
target[key] = {}
target = target[key]
origin = origin[key]
rec += '.'
else:
target[key] = None
break
return obj
下面是python 2.6中的一个例子:
>>> a = {1:1, 2:2, 3:3}
>>> dict((key,value) for key, value in a.iteritems() if key == 1)
{1: 1}
过滤部分是if语句。
如果你只想选择很多键中的几个,这个方法比delnan的答案要慢。
你可以使用python-benedict,它是dict的子类。
安装:pip install python-benedict
from benedict import benedict
dict_you_want = benedict(your_dict).subset(keys=['firstname', 'lastname', 'email'])
它在GitHub上开源:https://github.com/fabiocaccamo/python-benedict
声明:我是这个库的作者。
代码1:
dict = { key: key * 10 for key in range(0, 100) }
d1 = {}
for key, value in dict.items():
if key % 2 == 0:
d1[key] = value
代码2:
dict = { key: key * 10 for key in range(0, 100) }
d2 = {key: value for key, value in dict.items() if key % 2 == 0}
代码3:
dict = { key: key * 10 for key in range(0, 100) }
d3 = { key: dict[key] for key in dict.keys() if key % 2 == 0}
所有代码段的性能都用timeit度量,使用number=1000,并为每段代码收集1000次。
对于python 3.6,三种过滤字典键的方式的性能几乎相同。对于python 2.7,代码3略快一些。
构造一个新词典:
dict_you_want = {key: old_dict[key] for key in your_keys}
使用字典理解。
如果你使用的版本缺少它们(如Python 2.6及更早版本),请将其改为dict((key, old_dict[key]) for…)。它是一样的,只是更丑。
注意,与jnnnnn版本不同的是,对于任何大小的old_dicts具有稳定的性能(仅取决于your_keys的数量)。无论是速度还是内存。因为这是一个生成器表达式,所以它一次处理一个项,并且不会查看old_dict的所有项。
把所有东西都移走:
unwanted = set(keys) - set(your_dict)
for unwanted_key in unwanted: del your_dict[unwanted_key]
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录