Now it’s certainly possible that right now you do in fact have a good use case for sorting a dictionary (for example maybe you’re sorting keys in a dictionary of attributes), but keep in mind that you’ll need to sort a dictionary very rarely. If you can get away with using a list of tuples in your code (because you don’t actually need a key-value lookup), you probably should use a list of tuples instead of a dictionary.īut if key lookups are what you need, it’s unlikely that you also need to loop over your dictionary. 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. There are many other intricate sorting methods and tricks you could use with dictionaries (or any iterable object), but for now hopefully these examples have provided a good starting point.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 Likewise we could list the odd class sizes first, and perform many other algorithms to get our sort exactly how we want. > sorted(trans.values(), key=evens1st, reverse=True) Using the evens1st sorting function, gives us the following output: If we want to organize the class sizes with the even numbers first and odd numbers second, we could do so with a definition like this: Now let's say we have a dictionary keeping track of the number of students in a class for each of these months, like so: > sorted(month.values(), key=repeats, reverse=True) Using the function can be performed as follows: # Count the max occurrences of each unique letterĬounts = If we wanted to sort our key/value strings by the number of repeated letters in each string, we could define our own custom method to use in the sorted key argument: > for i in sorted(month, key=numbermap._getitem_)] # Assuming the keys in both dictionaries are EXACTLY the same: To return the months in order, we'll use a list comprehension again: > sorted(month, key=numbermap._getitem_)Īs we can see, it still returned a sorted list of its first argument (month). Unlike Python lists or tuples, the key and value pairs in dict objects are not in any particular order, which means we can have a dict like this: The values can be objects of any type (dictionaries can even be nested with other dictionaries) and the keys can be any object so long as it's hashable, meaning basically that it is immutable (so strings are not the only valid keys, but mutable objects like lists can never be used as keys). The dict (dictionary) class object in Python is a very versatile and useful container type, able to store a collection of values and retrieve them via keys. Note: If you want to sort a list, tuple or object in Python, checkout this article: How to Sort a List or Tuple in Python Last Updated: Wednesday 29 th December 2021
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |