在有序字典列表中搜索列表

searching for a list in a list of ordered dictionaries

所以我有一个有序字典列表,它们都有 'name' 键,这些键将字符串作为值,然后是一系列其他键,它们将整数作为值。我还有一个与有序字典列表分开的整数列表。我想搜索有序词典列表,看看是否有任何词典包含列表中的所有整数,如果有,该列表中的 'name' 值是什么。有什么办法吗?

即我有一个字典列表,里面有这样的字典:

dict = OrderedDict({('name' : 'John'), ('int1': 5), ('int2': 3), ('int3': 1)}), OrderedDict({('name': 'Jack'), ('int1': 1), ('int2': 6), ('int3': 7)}) 

然后是整数列表,例如:list = [3, 2, 5]

如果列表与任何有序词典中的整数匹配,我希望返回名称(在上述情况下,John)。

这可能是非常基础的,在这种情况下我很抱歉,我对 python 和一般编码还很陌生。我已经搜索了几个小时,但没有找到任何我能理解的内容。

如果我理解你的问题(不是示例数据或 John 的结果是正确的),你可能正在寻找

dicts = [
    {"name": "John", "int1": 5, "int2": 3, "int3": 1},
    {"name": "Jack", "int1": 1, "int2": 6, "int3": 7},
    {"name": "Mallory", "int1": 1, "int2": 6, "int3": 3},
]


def find_with_keyset(dicts, keyset):
    for dict in dicts:
        if all(
            key in dict and dict[key] == value
            for (key, value) in keyset.items()
        ):
            yield dict


def find_first_with_keyset(dicts, keyset):
    for result in find_with_keyset(dicts, keyset):
        return result


for match in find_with_keyset(dicts, {"int2": 6}):
    print(match["name"])

print("---")

print(find_first_with_keyset(dicts, {"int1": 5, "int2": 3, "int3": 1}))

这会打印出来

Jack
Mallory
---
{'name': 'John', 'int1': 5, 'int2': 3, 'int3': 1}

这个想法是 find_with_keyset 生成器函数根据关键子集过滤给定的字典迭代;为了便于使用,find_first_with_keyset 将 return 第一场比赛,或 None.

要将 [1, 2, 3] 变为 {'int1': 1, ...},您可以使用例如{f'key{i}': value for (i, value) in enumerate([1, 2, 3], 1)}.