How to sort a dictionary by key and value in Python?

How to sort a dictionary by key and value in Python?

Hello, Everyone. Today I?ll give short tips about dictionary sorting in Python (Python3). As we all know that dictionaries are inherently orderless, but other types, such as list and tuples are not. It is not possible to sort a dictionary, but we can make a representation of a dictionary that is sorted. So You need an ordered data type to represent sorted keys or values, which will be a list ? probably a list of tuples.

Image for postDictionary in Python (Source)Image for postProcess of sorting dictionaries

As we can see in the first figure dictionaries in python are a set of key-value pairs where each pair of key-value is called an item. Now let’s focus on the main issue: Dictionaries can be sorted by keys or values. As it is delineated in the second figure we can sort keys(), values(), and items() of a dictionary. Let?s focus on sorting by values()first.

sorting dictionary by value

Let us have a dictionary consisting of several well-renowned organizations as keys() and their foundation year as values(). So we want to have a sorted dictionary where the oldest organization items will be the first element and the youngest organization will be the last one.

d = {“Apple”: 1976, “Microsoft”:1975, “Facebook”:2004, “Sony”:1946, “IBM”:1911, “Amazon”: 1994 }

As we can see in the dictionary d, IBM is the oldest organization hence it will be the first key of the sorted dictionary and Facebook will be the last.

print(sorted(d.items(), key = lambda kv:kv[1]))print(sorted(d.items(), key = lambda kv:kv[1], reverse = True))print(dict(sorted(d.items(), key = lambda kv:kv[1])))sort_d = dict(sorted(d.items(), key = lambda kv:kv[1]))print(sort_d)


[(‘IBM’, 1911), (‘Sony’, 1946), (‘Microsoft’, 1975), (‘Apple’, 1976), (‘Amazon’, 1994), (‘Facebook’, 2004)][(‘Facebook’, 2004), (‘Amazon’, 1994), (‘Apple’, 1976), (‘Microsoft’, 1975), (‘Sony’, 1946), (‘IBM’, 1911)]{‘IBM’: 1911, ‘Sony’: 1946, ‘Microsoft’: 1975, ‘Apple’: 1976, ‘Amazon’: 1994, ‘Facebook’: 2004}{‘IBM’: 1911, ‘Sony’: 1946, ‘Microsoft’: 1975, ‘Apple’: 1976, ‘Amazon’: 1994, ‘Facebook’: 2004}

Since we?re sorting d.items(), which is a list of tuples where keys()are the first parameter and values() are the second parameter of each tuple. For sorting the list of tuples we?ve chosen the values i.e., the second parameter of each tuple as key. In the first line, the key is defined as a lambdafunction where the key value is the second parameter of the items. This sort will create a list of sorted tuples. we can just make it a dictionary using the dict() function as shown in the third line of code. We can also reverse the sorting which in result creates a list of tuples with the newest one in first and the oldest one will be the last item as indicated in the second line of the code. We can also save the sorted dictionary to another name as shown above.

sorting dictionary by key

print(sorted(d.items()))print(dict(sorted(d.items())))print(dict(sorted(d.items(), key = lambda kv:kv[0])))print(sorted(d.items(), reverse = True))


[(‘Amazon’, 1994), (‘Apple’, 1976), (‘Facebook’, 2004), (‘IBM’, 1911), (‘Microsoft’, 1975), (‘Sony’, 1946)]{‘Amazon’: 1994, ‘Apple’: 1976, ‘Facebook’: 2004, ‘IBM’: 1911, ‘Microsoft’: 1975, ‘Sony’: 1946}{‘Amazon’: 1994, ‘Apple’: 1976, ‘Facebook’: 2004, ‘IBM’: 1911, ‘Microsoft’: 1975, ‘Sony’: 1946}[(‘Sony’, 1946), (‘Microsoft’, 1975), (‘IBM’, 1911), (‘Facebook’, 2004), (‘Apple’, 1976), (‘Amazon’, 1994)]

As we know the keys() here in dictionary d are strings then the sorting by the key will create a list of tuples in alphabetical order in the keys() of each item and using dict() function the dictionary is formed. we can also use the lambda function to define the key which is almost unnecessary, I?ve just shown to make a comparison in defining the key in sorting.

That?s it. Please visit my profile to get more stories on machine learning and data analysis. Any kind of suggestions and criticisms are highly appreciated. Here is my previous stories based on a Graduate course offered by Inha University, Rep of Korea:

Previous stories:

Part-1: Basic python and installationPart-2: Chapter-2: Python Data Structure ? Data TypePart-3: Control Statements (Loops) in PythonPart:4: Python Functions & ModulesPart:5: Object-Oriented Programming in Python ? Schafer & DataCamp.Part-6: The types & procedure of Machine LearningPart-7: Feature Engineering for Machine Learning

Reference Links:


No Responses

Write a response