简体   繁体   English

以元组为值的字典比较

[英]Dictionary comparison with tuple as values

I'm creating a simple dictionary comparison to search and match items. 我正在创建一个简单的字典比较来搜索和匹配项目。 In this basic forms it works as expected. 以这种基本形式,它可以按预期工作。

def findOrders(lst, **kwargs):
    return [k for k in lst if kwargs.items() <= k.items()]

lst = [i for i in [ {'type':'esimene', 'id':1},
                    {'type':'teine', 'id':2},
                    {'type':'kolmas', 'id':3}]]

print(findOrders(lst, type='esimene'))

Now I would like to compare/match by multiple 'types' using a tuple as a keyword/values: 现在,我想使用元组作为关键字/值来比较/匹配多个“类型”:

findOrders(lst, type=('esimene', 'teine'))

What would be the best way to do this? 最好的方法是什么?

Could I create a generator that flattens the tuple to 'type':'esimene' and 'type':'teine' and then runs the comparison? 我可以创建一个将元组展平为'type':'esimene'和'type':'teine'的生成器,然后运行比较吗? What would it look like? 它会是什么样子?

Efficiency is also important this function will have heavy usage. 效率也很重要,此功能将被大量使用。

You could check if the the type parameter contains the type property of each item: 您可以检查type参数是否包含每个项目的type属性:

In [8]: def findOrders(lst, **kwargs):
   ...:     return [k for k in lst if k["type"] in kwargs["type"]]

In [9]: print(findOrders(lst, type='esimene'))
[{'type': 'esimene', 'id': 1}]

In [10]: print(findOrders(lst, type=('esimene',  'teine')))
[{'type': 'esimene', 'id': 1}, {'type': 'teine', 'id': 2}]

If you want to keep the current logic with the id comparison as well: 如果您还想保留当前逻辑与id比较:

In [32]: def findOrders(lst, **kwargs):
    ...:     return [k for k in lst if k["type"] in kwargs.get("type", (k["type"], )) and k["id"] ==
    ...: kwargs.get("id", k["id"])]
    ...:
    ...:
    ...:

In [33]: print(findOrders(lst, id=1))
[{'type': 'esimene', 'id': 1}]

In [34]: print(findOrders(lst, type=('esimene',  'teine')))
[{'type': 'esimene', 'id': 1}, {'type': 'teine', 'id': 2}]

In [35]: print(findOrders(lst, type=('esimene', 'teine'), id=2))
[{'type': 'teine', 'id': 2}]

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

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