在包含特定字符串的python字典中过滤项目 [英] filter items in a python dictionary where keys contain a specific string

查看:318
本文介绍了在包含特定字符串的python字典中过滤项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个C代码开发python的东西。我知道如何在C中执行以下操作(因此在应用于python的C语言逻辑中),但我想知道Python的做法是什么。



我有一个字典d,我想操作一个子集的项目,只有那些key(string)包含一个特定的子字符串。



即C逻辑将是:

 用于d中的键:
如果key_string在key中:
#do
else
#不做任何操作,继续

我想象的是python版本会像

  filtered_dict = crazy_python_syntax(d,substring)
用于键,filtered_dict.iteritems中的值( ):
#做某事

我在这里发现了很多关于过滤的帖子字典,但找不到一个涉及到这一点。



我的字典不是嵌套的,我使用的是python 2.7

解决方案

字幕理解如何?

  filtered_dict = {k:v for k,v in d.iteritems()if filter_string in k} 

一个你看到它,它应该是不言自明的,因为它看起来像英文很好



此语法需要Python 2.7或更高版本。



在Python 3中,只有 dict.items() ,而不是code> iteritems()所以你可以使用:

  filtered_dict = {k:v for (k,v)in d.items()if filter_string in k} 


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.

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.

i.e. the C logic would be:

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

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

解决方案

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.

In Python 3, there is only dict.items(), not iteritems() so you would use:

filtered_dict = {k:v for (k,v) in d.items() if filter_string in k}

这篇关于在包含特定字符串的python字典中过滤项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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