Gerasimos
Gerasimos

Reputation: 83

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). 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' ). 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 (e.g tuples). Lastly, I want to mention that "ID" is a string. Is there something I am missing or is iterating over the whole list for each insertion the only solution?

Thanks in advance

Upvotes: 1

Views: 436

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308138

Unfortunately bisect doesn't allow you to give a key parameter like sorted does. 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. 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)))

Upvotes: 3

Related Questions