我有一个字典,里面有一大堆词条。我只对其中的几个感兴趣。有什么简单的方法可以把其他的都剪掉吗?
当前回答
略为优雅的词典理解:
foodict = {k: v for k, v in mydict.items() if k.startswith('foo')}
其他回答
下面是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的答案要慢。
略为优雅的词典理解:
foodict = {k: v for k, v in mydict.items() if k.startswith('foo')}
我们可以这样简单地处理函数:
>>> dict_filter = lambda x, y: dict([ (i,x[i]) for i in x if i in set(y) ])
>>> large_dict = {"a":1,"b":2,"c":3,"d":4}
>>> new_dict_keys = ("c","d")
>>> small_dict=dict_filter(large_dict, new_dict_keys)
>>> print(small_dict)
{'c': 3, 'd': 4}
>>>
这是我的方法,支持嵌套字段,如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
这个函数可以做到:
def include_keys(dictionary, keys):
"""Filters a dict by only including certain keys."""
key_set = set(keys) & set(dictionary.keys())
return {key: dictionary[key] for key in key_set}
就像delnan的版本一样,这个版本使用字典理解,并且对于大型字典具有稳定的性能(仅取决于您允许的键数,而不是字典中的键总数)。
就像MyGGan的版本一样,这个版本允许您的键列表包含字典中可能不存在的键。
作为奖励,这里是反向的,在这里你可以通过排除原始的某些键来创建字典:
def exclude_keys(dictionary, keys):
"""Filters a dict by excluding certain keys."""
key_set = set(dictionary.keys()) - set(keys)
return {key: dictionary[key] for key in key_set}
注意,与delnan版本不同的是,该操作不是在适当的位置完成的,因此性能与字典中的键数有关。但是,这样做的好处是该函数不会修改所提供的字典。
编辑:添加了一个单独的功能,用于从字典中排除某些键。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录