简体   繁体   English

Python dict更改顺序-如何获得第一次出现?

[英]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.

相关问题 如何在python数据框中的列中获取值的第一次出现 - How to get the 1st occurence of a value in a column in python dataframe 如何在 python 中准确获取字典第一行的元素 - how to get exactly element of 1st row of dictionary in python 如何在 python 中获得一年中的第一个营业日期? - How to get 1st business date of year in python? 如何使用Python获取PCA的第一主要组件? - How to get the 1st Principal Component by PCA using Python? Python如何获取日期令牌的第一个元素 - Python How to get 1st element of date token Python:如何从列表字典中计算最小值、最大值、中值、第一和第三四分位数? - Python: how to compute min, max, median, 1st and 3rd quartiles from a dict of lists? for循环只使用dict中的第一个键 - for loop only using 1st key in dict 如何使用循环而不是方法获取句子字符串中每个单词大写的第一个字母? 在 python - How to get the 1st letter of each word capital in a string of sentence using loops but not methods? in python 如何迭代数据框名称列表以获取列表中每个数据框第一行的第一个值 - How to iterate of a list of dataframe's name to get the 1st value of 1st row of every dataframe in the list 尝试从python 3的第一个存储中获取第一个属性 - try to get the first attributes from the 1st store in python 3
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM