Sorting dictionaries in python by key

Python Sort Dictionary by Key

We can sort the dictionary by key using a sorted() function in Python. It can be used to sort dictionaries by key in ascending order or descending order. When we pass the dictionary into the sorted() function by default it sorts the keys of the dictionary and returns them as a list.

This function sorts iterable objects like lists, tuples, sets, and dictionaries. In this article, I will explain how to sort a dictionary by key in ascending/descending order using Pyhton sorted() function.

1. Quick Examples of Sort Dictionary by Key in Python

Following are quick examples of sorting dictionaries by key.

 # Below are the quick examples # Example 1: Sort the dictionary by key in ascending order new_dict = dict(sorted(my_dict.items())) # Example 2: Sort the dictionary by key in descending order new_dict = dict(sorted(my_dict.items(), reverse = True)) # Example 3: Sort the dictionary by key using dict comprehension Keys = list(my_dict.keys()) Keys.sort() new_dict = # Example 4: Sort only keys using sorted() print(sorted(my_dict)) # Example 5: Sort the dictionary by keys using items() new_dict = dict(sorted(my_dict.items(), key=lambda item: item[0])) 

2. What is Python Dictionary

A Python dictionary is a collection that is unordered, mutable, and does not allow duplicates. Each element in the dictionary is in the form of key:value pairs. Dictionary elements should be enclosed with <> and key: value pair separated by commas. The dictionaries are indexed by keys.

Let’s create a Python dictionary where, the ‘keys’ are ‘string’ type and ‘values’ are ‘int’ type.

 # Create dictionary my_dict = print(my_dict) print(type(my_dict)) 

python Sort Dictionary key

3. Sort Python Dictionary by Key in Ascending Order

The sorted() function in Python is used to sort a dictionary by key, By default, this function takes the dictionary as input, sorts the keys in dict, and returns only keys as a list in sorted order.

Читайте также:  METANIT.COM

If we want to get the sorted dictionary by keys in the form of the dictionary, we should use dictionary items() as input to the sorted() function. This returns the list of tuples with the sorted values and use this result in dict() function to get the dictionary where the key-value pairs are in ascending order.

 # Create dictionary my_dict = print(my_dict) print(type(my_dict)) # Sort the dictionary by key in ascending order result = sorted(my_dict.items()) print(result) # Convert to dictionary new_dict = dict(result) print(new_dict) 

python sort dictionary keys

Yields below output.

  • The items() method returns dictionary elements as tuples in a list.
  • sorted() function sorts the list of tuples.
  • dict() convert the sorted list of tuples back to a dictionary.

4. Sort Dictionary by key in Descending Order

To sort the Python dictionary by key in descending order use the ‘ reverse ‘ param as ‘ True ‘ and then pass it into the sorted() function. I have a dedicated article on sorting in reverse order in Python.

 # Sort the dictionary by key in descending order new_dict = dict(sorted(my_dict.items(), reverse = True)) print(new_dict) # Output:

Explanation:

  • The items() method returns dictionary elements as tuples in a list.
  • sorted() function sorts the list of tuples.
  • reverse = True param to sorted() sort the values in descending order.
  • dict() convert the sorted list of tuples back to a dictionary.

5. Using Dictionary Comprehension Sort by Key

Alternatively, using dictionary comprehension we can sort the dictionary by key. In order to sort the dictionary using comprehension first, we have to sort the list of keys from the dictionary using the list.sort() function and iterate the list using for loop, for each iteration add a new sorted key to the new dictionary in a comprehension.

 # Sort the dictionary by key using dict comprehension Keys = list(my_dict.keys()) Keys.sort() new_dict = print(new_dict) # Output: #

6. Sort Only Dictionary Keys using sorted()

When we pass the Python dictionary into sorted() function by default it will sort the keys of the dictionary and returns only keys. Note that the returned list contains only the sorted keys.

 # Sort only keys using sorted() print(sorted(my_dict)) # Output: # ['Apple', 'kiwi', 'papaya', 'pomegranate', 'strawberry'] 

7. Sort Python Dictionary by Keys using items()

We can also sort the dictionary by keys using the items() function along with the lambda function. Pass the items() function and lambda function into the sorted() function, it will sort the dictionary by keys and finally, get the sorted dictionary by keys using the dict() function.

 # Sort the dictionary by keys using items() new_dict = dict(sorted(my_dict.items(), key=lambda item: item[0])) print(new_dict) # Output: #

8. Conclusion

In this article, I have explained how to sort a dictionary by key in ascending/descending order using Pyhton sorted() function. And also explained using dictionary comprehension and items() function to sort the dictionary by keys with examples.

Читайте также:  Use math in python
  • How to Sort a List of Tuples in Python
  • Python Sort List Descending
  • Python Sort Array Values
  • Python Sort List in Reverse Order
  • Python Sort List of Numbers or Integers
  • Python Sort List Alphabetically
  • Sort using Lambda in Python
  • How to Sort List of Strings in Python
  • How to Sort Dictionary by Value in Python
  • Sort Set of Values in Python
  • Python Sort Dictionary
  • Sort List of Dictionaries by Value in Python

References

You may also like reading:

Источник

Python Sort Dictionary by Key – How to Sort a Dict with Keys

Shittu Olumide

Shittu Olumide

Python Sort Dictionary by Key – How to Sort a Dict with Keys

Sorting is a fundamental operation in computer programming that involves arranging elements in a specific order.

Whether you’re working with numbers, strings, or complex data structures, sorting plays a crucial role in organizing and manipulating data efficiently.

From small arrays to large datasets, sorting algorithms allow programmers to solve a wide range of problems, from searching for specific values to optimizing data access and analysis.

In this article, we will explore how to sort a dictionary with keys in Python. We will break down the steps for easy follow up and understanding. I recommend that you be familiar with the Python programming language to get the most out of this article.

What is a Python Dictionary?

In Python, dictionaries are a powerful data structure used to store key-value pairs. They provide a convenient way to organize and retrieve data based on unique keys. But there may be situations where you need to sort a dictionary by its keys in a specific order.

A key in Python refers to the unique identifier associated with a specific value. It serves as a way to access and retrieve values from the dictionary based on their corresponding keys. Keys in a dictionary can be of any immutable data type, such as strings, numbers (integers or floats), or tuples. The key must be unique within the dictionary, meaning that no two keys can have the same value.

Ways to Sort a Dict by Keys in Python

Method 1: Using the sorted() Function

The simplest way to sort a dictionary by its keys is by using the sorted() function along with the items() method of the dictionary.

Читайте также:  Add image to pdf python

The items() method returns a list of key-value pairs as tuples. By passing this list to the sorted() function, we can sort the tuples based on their first element (the keys).

my_dict = sorted_dict = dict(sorted(my_dict.items())) print(sorted_dict) 

In this example, the sorted() function takes the my_dict.items() list and returns a new sorted list of tuples. We use the dict() constructor to convert the sorted list back into a dictionary.

Method 2: Using a List of Tuples

If you prefer a more manual approach, you can convert the dictionary to a list of tuples, sort the list using any sorting technique available in Python, and then convert it back to a dictionary.

my_dict = sorted_list = sorted(my_dict.items()) sorted_dict = <> for key, value in sorted_list: sorted_dictSorting dictionaries in python by key = value print(sorted_dict) 

In this example, we used the sorted() function to sort the my_dict.items() list. Then, a new empty dictionary, sorted_dict , is created. The sorted list is iterated over, and each key-value pair is added to the sorted_dict using assignment.

Method 3: Using the collections.OrderedDict Class

Another approach to sorting a dictionary by key is to use the collections.OrderedDict class from the Python standard library.

This class is a dict subclass that remembers the order of its elements based on the insertion order. We can leverage this feature to achieve key-based sorting.

from collections import OrderedDict my_dict = sorted_dict = OrderedDict(sorted(my_dict.items())) print(sorted_dict) 

In this example, the sorted() function is used to sort the my_dict.items() list, and then the sorted list is passed to the OrderedDict() constructor to create a new dictionary with the sorted order.

Conclusion

In Python, you can sort a dictionary by its keys using various methods. In this article, we explored three approaches: using the sorted() function, utilizing the collections.OrderedDict class, and manually sorting a list of tuples. Each method provides a different level of control and flexibility.

By using the sorted() function, we can quickly sort a dictionary by key and obtain a new dictionary as the result. If preservation of the insertion order is crucial, the collections.OrderedDict class is a suitable choice.

For those who prefer a more manual approach, converting the dictionary to a list of tuples, sorting the list, and then creating a new dictionary can provide more customization options.

Let’s connect on Twitter and on LinkedIn. You can also subscribe to my YouTube channel.

Источник

Оцените статью