![]() They’re very fast at retrieving values for keys.īut dictionaries take up more space than a list of tuples. In fact, when you’re considering looping over a dictionary you might ask “do I really need a dictionary here”?ĭictionaries are used for key-value lookups: you can quickly get a value given a key. When you’re about to sort a dictionary, first ask yourself “do I need to do this”? We can’t sort a dictionary in-place, but we could get the items from our dictionary, sort those items using the same technique we used before, and then turn those items into a new dictionary: Unlike lists, there’s no sort method on dictionaries. ![]() What if we already have our items in a dictionary and we’d like to sort that dictionary? So as long as the keys are comparable to each other with the less than operator ( <), sorting 2-item tuples of key-value pairs should always sort by the keys. The keys in a dictionary should always compare as unequal (if two keys are equal, they’re seen as the same key). You might be thinking: it seems like this sorts not just by keys but by keys and values. I’ve written an article on tuple ordering that explains this in more detail. Def compare_two_item_tuples ( a, b ): """This is the same as a < b for two 2-item tuples.""" if a != b : # If the first item of each tuple is unequal return a < b # Compare the first item from each tuple else : return a < b # Compare the second item from each tuple
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |