[英]Python dict changes ordering - how get 1st occurence?
I am trying for 2 hours to get the first occurrence of a key-value pair that has a specific value. 我尝试了2个小时,才第一次出现具有特定值的键值对。 (tuples are keys, values are integers).
(元组是键,值是整数)。
Why is this relevant ? 为什么如此相关? The dict is sorted by the keys.
字典按键排序。
I can pprint() the dict and I see the first occurence is the one I want - BUT iterating over the dict and putting out the first occurence using itemgetter outputs the WRONG tuple. 我可以对dict进行pprint()处理,然后看到第一个匹配项是我想要的-但是迭代该dict并使用itemgetter输出WRONG元组输出第一个匹配项。
The runnable code is here: https://repl.it/repls/WatchfulStridentLight The lines that are relevant are 54 to 86 (mind the large debug sections) 可运行的代码在这里: https : //repl.it/repls/WatchfulStridentLight相关的行是54到86(请注意较大的调试部分)
pprint([k for k,v in allsmall.items() if v>=maxb]) #HERE, the 2nd tuple IS WHAT I WANT, the correct value
This would be my go-to solution to get that first occurence from pprint: 这是从pprint首次出现的首选解决方案:
print(max(allsmall.items(), key=operator.itemgetter(1))[0]) #almost minimum
But it gets the 2nd occurence ?! 但是它会第二次出现 ?!
This completely breaks the ordering: 这完全破坏了顺序:
print(max(allsmall.items(), key=operator.itemgetter(0))[0])
Expected: First occurrence can be accessed because pprint() prints it correctly 预期:因为pprint()正确打印,所以可以访问第一次出现
Actual: I get second occurence.... 实际:我第二次出现。
Use OrderedDict
. 使用
OrderedDict
。 It preserves insertion order so you should get the first occurrence. 它保留插入顺序,因此您应该首先出现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.