简体   繁体   English

Pythonic方法获取字典中的所有元素,落在两个键之间?

[英]Pythonic way to fetch all elements in a dictionary, falling between two keys?

I have a dictionary object, and I want to extract a subset of the dictionary (ie return another dictionary), which contains all elements of the parent dictionary where the key matches a certain criteria. 我有一个字典对象,我想提取字典的一个子集(即返回另一个字典),其中包含密钥与特定条件匹配的父字典的所有元素。

For example: 例如:

parent_dict = {1: 'Homer',
               2: 'Bart',
               3: 'Lisa',
               4: 'Marge',
               5: 'Maggie'
               }


def filter_func(somedict, key_criteria_func):
    pass

I want to write (in a pythonic way), filter_func , so that I can call it like this: 我想写(以filter_func方式), filter_func ,以便我可以像这样调用它:

filter_func(parent_dict, ">2 and <4")

which will return the new dict: 这将返回新的字典:

{ 3: 'Lisa' }

What is the most pythonic way to write filter_func? 编写filter_func?的最filter_func?方法是filter_func?

To keep things simple, I will limit the criteria to simple boolean operations. 为了简单起见,我将标准限制为简单的布尔运算。

[[Edit]] [[编辑]]

This is the output when I try the following command: 这是我尝试以下命令时的输出:

>>> {key:val for key,val in parent_dict.iteritems() if 2 < key < 4 }
  File "<stdin>", line 1
    {key:val for key,val in parent_dict.iteritems() if 2 < key < 4 }
               ^
SyntaxError: invalid syntax

BTW, I'm running Python 2.6.5 顺便说一下,我正在运行Python 2.6.5

Solution

Starting from python 2.7, you can use dictionary comprehension. 从python 2.7开始,您可以使用字典理解。 There are like list comprehensions, but applied to a dictionary: 有类似列表推导,但应用于字典:

>>> parent_dict = {1: 'Homer',
...                2: 'Bart',
...                3: 'Lisa',
...                4: 'Marge',
...                5: 'Maggie'
...                }
>>> {key:val for key,val in parent_dict.iteritems() if 2 < key < 4 }
1: {3: 'Lisa'}

You probably don't need to make it a function, but if you do, you can just use a lambda function as a filter: 您可能不需要将其作为函数,但如果这样做,您可以使用lambda函数作为过滤器:

>>> def filter_func(somedict, key_criteria_func):
...     return {k:v for k, v in somedict.iteritems() if  key_criteria_func(k)}
... 
... filter_func(parent_dict, lambda x: 2 < x < 4)
2: {3: 'Lisa'}

For Python 2.6.5 and all version before 2.7, replace the dict comprehension with: 对于Python 2.6.5和2.7之前的所有版本,将dict理解替换为:

dict((k,v) for k,v in parent_dict.iteritems() if 2 < k < 4)

Why a lambda function ? 为什么lambda功能?

Lambda function are not magic, it's just a way to easily create fonction on the fly. Lambda函数不是魔术,它只是一种轻松创建动态的方法。 You can do everything you do with lambda witout it, the only difference is that lambdas are expression, and therefor can be used directly between parenthis. 你可以用lambda做你所做的一切,唯一的区别是lambda是表达式,因此可以在parenthis之间直接使用。

Compare: 相比:

>>> func = lambda x: 2 < x < 4
>>> func(3)
True

With: 附:

>>> def func(x):
...    return 2 < x < 4
...
>>> func(3)
True

It's exactly the same and produce the same function, except the lambda function won't have a name. 它完全相同并产生相同的功能,除了lambda函数没有名称。 But you don't care, on your case you don't need a name, you just need a reference to call it, and the variable func contains this reference. 但你不在乎,在你的情况下你不需要名字,你只需要一个引用来调用它,变量func包含这个引用。

The lambda syntax is weird because: lambda语法很奇怪,因为:

  • You don't need parenthesis for the parameters (you don't even need parameter) 参数不需要括号(甚至不需要参数)
  • you don't do def var(param): but var = lambda param: . 你不做def var(param):var = lambda param: . Nothing magic, it's just syntax 没有什么神奇的,它只是语法
  • you can't make a 2 lines lambda : the return result must fit in one instruction. 你不能制作2行lambda :返回结果必须适合一条指令。
  • you don't use the return keyword: the right part of the lambda is returned automatically 你不使用return关键字:lambda的右边部分是自动返回的

Now the nice thing with a lamda, is that since it's an expression, you can use it between parenthese, meaning you can create and pass your fonction à the same time. 现在lamda的好处是,因为它是一个表达式,你可以在括号之间使用它,这意味着你可以同时创建和传递你的功能。

Compare: 相比:

>>> filter_func(parent_dict, lambda x: 2 < x < 4)

With: 附:

>>> def func(x):
...    return 2 < x < 4
...
>>> filter_func(parent_dict, func)

It's exactly the same. 它完全一样。 The lambda is just shorter. lambda只是更短。

The hard part here is to understand that you can pass a function as a parameter in Python because everything in Python is an object, including functions. 这里最难的部分是要理解你可以在Python中将函数作为参数传递,因为Python中的所有东西都是一个对象,包括函数。

You can even do this: 你甚至可以这样做:

>>> def func():
...    print "test"
...
>>> ref_to_func = func # assign the function refence to another var
>>> del func # delete this label
>>> ref_to_func() # call the function from this label
test

And you can even define a fonction on one line: 你甚至可以在一行上定义一个函数:

>>> def func(): print "test"
>>> func() 
test

But you can't do this: 但你不能这样做:

filter_func(parent_dict, def func(x): 2 < x 4 )

Which is where lambdas are useful. lambda是有用的。

dict((k,v) for k,v in parent_dict.iteritems() if 2 < k < 4)

这适用于Python 2.6.5。

对于python 2.5.2:

dict( (k,v) for k,v in parent_dict.iteritems() if k > 2 and k < 4 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM