首页 > 解决方案 > 有没有比这更 Pythonic 的方法来遍历字典键以查找值?

问题描述

这是一个示例字典,colors

{
    "Red" : {
        "members" : {
            "153950039532134112" : {
                "rank" : 1,
                "score" : 43,
                "time" : 1530513303
            }
        },
        "rank" : 2,
        "score" : 43
    },
    "Blue" : {
        "members" : {
            "273493248051539968" : {
                "rank" : 1,
                "score" : 849,
                "time" : 1530514923
            },
            "277645262486011904" : {
                "rank" : 2,
                "score" : 312,
                "time" : 1530513964
            },
            "281784064714487810" : {
                "rank" : 3,
                "score" : 235,
                "time" : 1530514147
            }
        },
        "rank" : 1,
        "score" : 1396
    }
}

为了这个例子,让我们假设这个字典中有更多的颜色命名键。现在,假设我正在寻找一个特定的会员 ID。

for key, value in colors.items():
    if member_id in value['members']:
        return True

有没有更简单的,可能是单行的方法来做到这一点?

标签: pythonpython-2.7dictionary

解决方案


any这是另一个与 生成器表达式结合使用的单行代码:

return any(member_id in color['members'] for color in colors.values())

推荐阅读