最快的方式查找词典项目会议2单独的标准

时间:2014-10-20 14:58:51

标签: python performance dictionary

我有一个包含3个元素的字典:URL,Speed,Online。

URL = text string (using it as the key)
Speed = integer
Online = True/False

我需要获取具有最低速度整数的字典项的键,其中Online = True。

速度对于脚本中的查找非常重要。

获得密钥的最快方法是什么?

循环就是我现在正在做的事情。有更快的东西吗?

dict = {'url1.com': [1, False],  'url2.com': [5, True],
              'url3.net': [2, False], 'url4.org': [3, True],
              'url5.net': [2, True]}

min = 99999
for key, first in dict.items():
    online = first[1]
    if online == True:
        speed = first[0]
        print speed

        if speed < min:
            current_key = key
            min = speed

print current_key

4 个答案:

答案 0 :(得分:3)

print min((x for x in data_dict.items() if x[-1][-1]),key=lambda x:x[-1])

是你可以做到这一点的一种方法,它使用生成器进行过滤步骤以避免循环两次

答案 1 :(得分:1)

似乎你无法摆脱必须通过所有键值对检查的事实。我想不出用一种方法来替换for。

你有一些无关的任务和事情。

min = 99999
for key, first in dict.items():
    if first[1]:
        if first[0] < min:
            min = first[0]
            current_key = key

print current_key

答案 2 :(得分:0)

for k, v in sorted(d.items(), key=lambda (x,y): y[0], reverse=True): # for py3.x do list(d.items())
    if all(v):
        print k
        break

答案 3 :(得分:0)

如果要优化速度,则需要使用除dict之外的其他内容来存储数据。在计算&#34;速度&#34;的值时您可以保留最后使用的变量中的最小值。然后,您不必再次查看字典中的每个项目,以确定哪个是最低值。