使用 python 在字典中使用具有某些条件的值查找键?

Find the keys using the values with some conditions in a dictionary using python?

我有这样的字典:

 {'1956': 21,
     '2188': 76,
     '1307': 9,
     '1305': 22,
     '2196': 64,
     '3161': 1,
     '1025': 22,
     '321': 60,
     '1959': 1,
     '1342': 7,
     '3264': 2}

每个键都是唯一的,我想从字典中获取那些值大于60的键。

输出如下:

  ['2188','2196']

我可以使用带有 if 条件的 get('key') 进行循环迭代,但那是一个漫长的过程,有什么捷径可以更高效地完成?

[k for k, v in mydict.items() if v > 60]
keyValue =  {'1956': 21,
     '2188': 76,
     '1307': 9,
     '1305': 22,
     '2196': 64,
     '3161': 1,
     '1025': 22,
     '321': 60,
     '1959': 1,
     '1342': 7,
     '3264': 2}

for key, value in keyValue.items():
    if value > 60:
        print(key)

# Or just:
print([key for key, value in keyValue.items() if value > 60])

如果你想在没有循环的情况下实现这个,并且顺序无关紧要,你可以试试这个:

dc = {'1956': 21, '2188': 76, '1307': 9, '1305': 22, '2196': 64, '3161': 1, '1025': 22, '321': 60, '1959': 1, '1342': 7, '3264': 2}

dc_val = sorted(dc.values(), reverse = True)
target_index = dc_val.index(60)
keys = sorted(dc.keys(), key = lambda x: dc[x])
target_keys = keys[-target_index:]
print(target_keys)

>>> ['2196', '2188']

这里我们要对字典按值进行排序,并选择值60的索引,并获取该索引之后的值对应的所有键。 所以先把倒序的值存入dc_val,为什么要倒序呢?因为万一有多个60,那么后面的方法就很关键了。因此,假设您有 2 个值为 60 的键,那么 dc_val 将具有:

[76, 64, 60, 60, 22, 22, 21, 9, 7, 2, 1, 1]

现在 target_index 将是列表中出现 60 的第一个索引,即 2,即 third指数。 然后 keys 保存根据值排序(未反转)的键。 然后我们的 target_keys 成为 third 最后一个元素之后的元素,我们可以像这样通过 target_index 访问它: keys[-target_index:].