How To Order By Key (alphabetically) In Defaultdict(list) For An Inverted Index
Solution 1:
Calling sorted()
on a dictionary returns just a list of the keys in sorted order. Dictionaries themselves have no inherent order, you cannot sort those.
Because you re-assigned the output of sorted()
back to self.index
, you've now lost your reference to the original defaultdict
.
Solution 2:
I do not believe dictionaries can be sorted in the sense you are referring to. If you want to view the dictionary sorted you can try the following:
sorted(self.index.items())
Note however that the result is not a dictionary - its just a list of (key, value) tuples which would be associated with each other in the original dictionary.
Solution 3:
I read this yesterday and i think it might be just what you are looking for. Its a Binary Heap implementation for Python dictionaries. It puts out its items in sorted order if you call a for on it.
http://code.activestate.com/recipes/117228-priority-dictionary/
Post a Comment for "How To Order By Key (alphabetically) In Defaultdict(list) For An Inverted Index"