简体   繁体   中英

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. (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.

The runnable code is here: https://repl.it/repls/WatchfulStridentLight The lines that are relevant are 54 to 86 (mind the large debug sections)

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:

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

Actual: I get second occurence....

Use OrderedDict . It preserves insertion order so you should get the first occurrence.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM