过滤 Python 字典中的项,其中键包含特定字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23862406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
filter items in a python dictionary where keys contain a specific string
提问by memo
I'm a C coder developing something in python. I know how to do the following in C (and hence in C-like logic applied to python), but I'm wondering what the 'Python' way of doing it is.
我是一名 C 编码员,正在用 python 开发一些东西。我知道如何在 C 中执行以下操作(因此在应用于 Python 的类 C 逻辑中),但我想知道“Python”的做法是什么。
I have a dictionary d, and I'd like to operate on a subset of the items, only those who's key (string) contains a specific substring.
我有一个字典 d,我想对项目的一个子集进行操作,只有那些键(字符串)包含特定的子字符串。
i.e. the C logic would be:
即 C 逻辑将是:
for key in d:
if filter_string in key:
# do something
else
# do nothing, continue
I'm imagining the python version would be something like
我想象 python 版本会是这样的
filtered_dict = crazy_python_syntax(d, substring)
for key,value in filtered_dict.iteritems():
# do something
I've found a lot of posts on here regarding filtering dictionaries, but couldn't find one which involved exactly this.
我在这里找到了很多关于过滤字典的帖子,但找不到一个完全涉及这个的帖子。
My dictionary is not nested and i'm using python 2.7
我的字典不是嵌套的,我使用的是 python 2.7
采纳答案by Jonathon Reinhart
How about a dict comprehension:
字典理解如何:
filtered_dict = {k:v for k,v in d.iteritems() if filter_string in k}
One you see it, it should be self-explanatory, as it reads like English pretty well.
你看到它,它应该是不言自明的,因为它读起来很像英语。
This syntax requires Python 2.7 or greater.
此语法需要 Python 2.7 或更高版本。
In Python 3, there is only dict.items()
, not iteritems()
so you would use:
在 Python 3 中,只有dict.items()
,而不是iteritems()
你会使用:
filtered_dict = {k:v for (k,v) in d.items() if filter_string in k}
回答by jspurim
input = {"A":"a", "B":"b", "C":"c"}
output = {k:v for (k,v) in input.items() if key_satifies_condition(k)}
回答by Burhan Khalid
Jonathon gave you an approach using dict comprehensions in his answer. Here is an approach that deals with your do somethingpart.
Jonathon 在他的回答中为您提供了一种使用 dict 理解的方法。这是一种处理您做某事部分的方法。
If you want to do something with the values of the dictionary, you don't need a dictionary comprehension at all:
如果你想对字典的值做一些事情,你根本不需要字典理解:
I'm using iteritems(
) since you tagged your question with python-2.7
我正在使用iteritems(
) 因为你用python-2.7标记了你的问题
results = map(some_function, [(k,v) for k,v in a_dict.iteritems() if 'foo' in k])
Now the result will be in a list with some_function
applied to each key/value pair of the dictionary, that has foo
in its key.
现在结果将在一个列表中,some_function
应用于字典的每个键/值对,foo
在它的键中。
If you just want to deal with the values and ignore the keys, just change the list comprehension:
如果您只想处理值而忽略键,只需更改列表理解:
results = map(some_function, [v for k,v in a_dict.iteritems() if 'foo' in k])
some_function
can be any callable, so a lambda would work as well:
some_function
可以是任何可调用的,因此 lambda 也可以工作:
results = map(lambda x: x*2, [v for k,v in a_dict.iteritems() if 'foo' in k])
The inner list is actually not required, as you can pass a generator expressionto map as well:
内部列表实际上不是必需的,因为您也可以将生成器表达式传递给映射:
>>> map(lambda a: a[0]*a[1], ((k,v) for k,v in {2:2, 3:2}.iteritems() if k == 2))
[4]
回答by Brendan F
Go for whatever is most readable and easily maintainable. Just because you can write it out in a single line doesn't mean that you should. Your existing solution is close to what I would use other than I would user iteritems to skip the value lookup, and I hate nested ifs if I can avoid them:
选择最易读且易于维护的内容。仅仅因为您可以将其写在一行中并不意味着您应该这样做。除了我会使用 iteritems 跳过值查找之外,您现有的解决方案接近于我将使用的解决方案,如果我可以避免它们,我讨厌嵌套 ifs:
for key, val in d.iteritems():
if filter_string not in key:
continue
# do something
However if you realllly want something to let you iterate through a filtered dict then I would not do the two step process of building the filtered dict and then iterating through it, but instead use a generator, because what is more pythonic (and awesome) than a generator?
但是,如果你真的想要一些东西让你遍历过滤的字典,那么我不会做构建过滤字典然后遍历它的两步过程,而是使用生成器,因为比发电机?
First we create our generator, and good design dictates that we make it abstract enough to be reusable:
首先我们创建我们的生成器,良好的设计要求我们让它足够抽象以便可以重用:
# The implementation of my generator may look vaguely familiar, no?
def filter_dict(d, filter_string):
for key, val in d.iteritems():
if filter_string not in key:
continue
yield key, val
And then we can use the generator to solve your problem nice and cleanly with simple, understandable code:
然后我们可以使用生成器通过简单易懂的代码很好地解决您的问题:
for key, val in filter_dict(d, some_string):
# do something
In short: generators are awesome.
简而言之:发电机很棒。
回答by Pulkit
You can use the built-in filter functionto filter dictionaries, lists, etc. based on specific conditions.
您可以使用内置的过滤器功能,根据特定条件过滤字典、列表等。
filtered_dict = dict(filter(lambda item: filter_str in item[0], d.items()))
The advantage is that you can use it for different data structures.
优点是您可以将它用于不同的数据结构。