【问题标题】:Find the keys using the values with some conditions in a dictionary using python?使用python在字典中使用具有某些条件的值查找键?
【发布时间】:2019-08-08 12:16:17
【问题描述】:

我有一本这样的字典:

 {'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']

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

【问题讨论】:

  • [k for k, v in dict.items() if v > 60][k for k in dict if dict[k] > 60]

标签: python dictionary key-value


【解决方案1】:
[k for k, v in mydict.items() if v > 60]

【讨论】:

  • 当然,这仍将花费与 for 循环相同的时间,只是更整洁
【解决方案2】:
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])

【讨论】:

    【解决方案3】:

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

    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,即 第三个 索引。 然后keys 保存根据它们的值排序(而不是反转)的键。 然后我们的 target_keys 成为 third 最后一个元素之后的元素,我们可以通过 target_index 访问它,如下所示:keys[-target_index:]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-28
      • 1970-01-01
      • 2020-12-16
      相关资源
      最近更新 更多