简体   繁体   English

将字典插入字典的排序列表

[英]Inserting a dictionary to a sorted list of dictionaries

I've been trying to insert a new dictionary to a sorted list of dictionaries while maintaining the order.我一直在尝试在保持顺序的同时将新字典插入到排序的字典列表中。 To sort the list of dictionaries I've used sample_dict = sorted(sample_dict, key=lambda k: k['ID']) It seems the only solution would be to iterate over the list and compare the ID of each entry with the previous one but this solution does not sound optimal (time-wise).为了对字典列表进行排序,我使用了sample_dict = sorted(sample_dict, key=lambda k: k['ID'])似乎唯一的解决方案是遍历列表并将每个条目的 ID 与前一个条目进行比较一个,但这个解决方案听起来不是最优的(时间方面)。 I have also found bisect library which allows entry insertion in lists while keeping the correct order but it seems it does not work with dictionaries ( throws TypeError: '<' not supported between instances of 'dict' and 'dict' ).我还找到了bisect库,它允许在列表中插入条目,同时保持正确的顺序,但它似乎不适用于字典( TypeError: '<' not supported between instances of 'dict' and 'dict' )。 I also want to mention that my entries contains a lot key-values pairs (21) and I am not sure if there are any alternatives to dictionaries (eg tuples).我还想提一下,我的条目包含很多键值对(21),我不确定是否有任何替代字典(例如元组)。 Lastly, I want to mention that "ID" is a string.最后,我想提一下“ID”是一个字符串。 Is there something I am missing or is iterating over the whole list for each insertion the only solution?是否有我遗漏的东西,或者是否为每个插入迭代整个列表是唯一的解决方案?

Thanks in advance提前致谢

Unfortunately bisect doesn't allow you to give a key parameter like sorted does.不幸的是bisect不允许您像sorted那样提供key参数。 But it's easy to get around it by keeping a list of tuples instead of dictionaries.但是通过保存元组列表而不是字典很容易绕过它。 Less-than on a tuple compares element by element, so if the first element of the tuple is your key then everything works.元组上的小于是逐个元素比较的,所以如果元组的第一个元素是你的键,那么一切正常。

sample_dict = sorted(((k['ID'], k) for k in sample_dict))

As mentioned in the comments, this still fails if two list items have the same ID because the comparison moves on to the second tuple element.正如评论中提到的,如果两个列表项具有相同的 ID,这仍然会失败,因为比较会转移到第二个元组元素。 The solution is to add another tuple element that is guaranteed to never be equal.解决方案是添加另一个保证永远不会相等的元组元素。

sample_dict = sorted(((k['ID'], index, k) for index,k in enumerate(sample_dict)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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