How to Sort a Python Dictionary by Key or Value


In this instructional, you’ll find out how to type a Python dictionary by its key or price.

When you’re running with a dictionary in Python, there are occasions while you’ll want to type its contents—by key or by price. As a Python dictionary is a key-value mapping, you’ll create a new dictionary that has the keys or values looked after as wanted.

In this instructional, we’ll get started by reviewing the fundamentals of Python dictionary. We’ll then be informed to create a new dictionary wherein the contents are looked after by key or by price, as wanted.

Python Dictionary Basics, Revisited

What is a Python Dictionary?

Dictionary is a integrated knowledge construction in Python. It shops pieces as key-value pairs. You can use the keys to glance up the corresponding values. As the keys uniquely establish the values, there must be no repetition of keys.

py_dict = "Python":"cool!","Learn":True
py_dict["Python"]
# Output: cool!

py_dict["Learn"]
# Output: True

Functionally, a dictionary is the same to a hash map. Therefore, it isn’t essentially an ordered knowledge construction. You can get admission to the contents of a dictionary in any arbitrary order, as long as you realize the keys.

Ordering of Items in a Dictionary

In previous variations of Python, you had to use an OrderedDict to maintain the order of the keys. However, from Python 3.7, you’ll be able to get admission to the pieces within the similar order wherein you upload them to the dictionary. 

Now that you just’ve realized the fundamentals of Python dictionaries, let’s find out how to create looked after copies of the dictionary.

⚙️ Note: You want to have Python 3.7 or later for the code on this instructional to paintings as anticipated. You can obtain the latest version of Python, or run the examples in Geekflare Online Python Editor.

How to Sort a Python Dictionary by Key

Look on the following symbol of the dessert menu at a café. There are two columns corresponding to the pieces at the menu and their respective costs.

python-dictionary-from-data

You can constitute this within the type of a Python dictionary by amassing the names of things as keys and their costs as values.

Let’s move forward and create the dictionary cakes, as proven under.

cakes = 
    "Ice cream":10,
    "Brownies":12,
    "Cheesecake":3,
    "Swiss roll":5,
    "Cookies":4,
    "Cup cake":2

Next, let’s create a dictionary sorted_desserts, the place the cakes are organized in alphabetical order. In the unique cakes dictionary, the names of the cakes are the keys. So you must type those keys in alphabetical order to create a new dictionary.

How to Access the Keys of a Python Dictionary

To do that, we’ll first get the keys of the dictionary after which type them in alphabetical order.

In Python, you’ll be able to use the integrated dictionary way .keys() to get a checklist of the entire keys within the dictionary.

Let’s name the .keys() way at the dessert dictionary to retrieve the keys, as proven under.

keys = cakes.keys()
print(keys)

#Output
['Ice cream', 'Brownies', 'Cheesecake', 'Swiss roll', 'Cookies', 
'Cup cake']

Calling Python’s integrated looked after() serve as with a checklist because the argument returns a new looked after checklist.

Next, let’s name the looked after() serve as with the checklist keys because the argument and retailer the looked after checklist within the variable sorted_keys.

sorted_keys = looked after(keys)
print(sorted_keys)

# Output
['Brownies', 'Cheesecake', 'Cookies', 'Cup cake', 'Ice cream', 'Swiss roll']

Now that we have got the keys looked after in alphabetical order, we will glance up the values corresponding to the keys in sorted_keys from the cakes dictionary, as proven under.

sorted_desserts = 
for key in sorted_keys:
  sorted_desserts[key] = cakes[key]

print(sorted_desserts)

# Output
'Brownies': 12, 'Cheesecake': 3, 'Cookies': 4, 'Cup cake': 2, 
'Ice cream': 10, 'Swiss roll': 5

Let’s extend at the above block of code:

  • Initialize sorted_desserts to be an empty Python dictionary.
  • Loop in the course of the keys checklist sorted_keys.
  • For every key in sorted_keys, upload an access to sorted_desserts by taking a look up the corresponding price within the cakes dictionary.

Using the for loop like this is regarded as verbose. In Python, there’s a extra concise selection the use of dictionary comprehension.

Dictionary Comprehension in Python

Python helps the usage of dictionary comprehension, identical to checklist comprehension. Dictionary comprehension permits you to create a new Python dictionary with only one line of code.

▶️ Here’s the overall assemble to use dictionary comprehension in Python.

# 1. you probably have each keys and values in two lists: list1, list2
new_dict = key:price for key,price in zip(list1,list2)

# 2. you probably have the keys, and will glance up the values
new_dict = key:price for key in <iterable>

Let’s use the second one assemble within the above cellular: new_dict = key:price for key in <iterable> to create a sorted_desserts dictionary.

In this situation:

  • iterable: the checklist sorted_keys
  • key: the important thing that we get admission to by looping via sorted_keys
  • price: glance up the worth corresponding to the important thing from the cakes dictionary, cakes[key]

Putting all of it in combination, we’ve the expression for dictionary comprehension, as proven under.

sorted_desserts = key:cakes[key] for key in sorted_keys
print(sorted_desserts)

'Brownies': 12, 'Cheesecake': 3, 'Cookies': 4, 'Cup cake': 2, 
'Ice cream': 10, 'Swiss roll': 5

From the above output, the cakes are organized in alphabetical order within the sorted_desserts dictionary.

How to Sort a Python Dictionary by Value

Next, we’ll find out how to type a Python dictionary by its values.

In the cakes dictionary, the values correspond to the costs of the cakes. You might need to type the dictionary by costs, both in expanding or reducing order.

▶️ You can use the integrated dictionary way .pieces() to get the entire key-value pairs. Each tuple is a key-value pair.

cakes.pieces()

dict_items([('Ice cream', 10), ('Brownies', 12), ('Cheesecake', 3), 
('Swiss roll', 5), ('Cookies', 4), ('Cup cake', 2)])

Each of the pieces is a tuple in itself. So you’ll be able to additionally index into every key-value pair to get admission to the keys and values personally.

dict_items = cakes.pieces()
for merchandise in dict_items:
  print(f"key:merchandise[0],price:merchandise[1]")

# Output
key:Ice cream,price:10
key:Brownies,price:12
key:Cheesecake,price:3
key:Swiss roll,price:5
key:Cookies,price:4
key:Cup cake,price:2

As we would really like to type by values, we’ll use the above way to get the worth at index 1 within the key-value pair.

How to Sort the Values of a Python Dictionary in Increasing Order

This time, we’ll use the looked after() serve as in conjunction with the not obligatory key parameter. key may also be any Python serve as, a integrated serve as, a user-defined serve as, or even a lambda function.

Note: lambda args: expression is the syntax for outlining lambda purposes in Python.

In this situation of sorting cakes by value, we’ve get admission to to dictionary pieces (key-value pairs). We’ll set key = lambda merchandise:merchandise[1] as we’d like to type by the worth (value).

As looked after() serve as returns a checklist by default, you must explicitly solid it into a dict, as proven under.

sorted_desserts = dict(looked after(cakes.pieces(), key=lambda merchandise:merchandise[1]))
print(sorted_desserts)

'Cup cake': 2, 'Cheesecake': 3, 'Cookies': 4, 'Swiss roll': 5, 
'Ice cream': 10, 'Brownies': 12

You too can rewrite the use of dictionary comprehension, as mentioned previous.

sorted_desserts = key:price for key, price in looked after(cakes.pieces(), 
key=lambda merchandise:merchandise[1])

print(sorted_desserts)

# Output
'Cup cake': 2, 'Cheesecake': 3, 'Cookies': 4, 'Swiss roll': 5, 
'Ice cream': 10, 'Brownies': 12

In sorted_desserts, Cup Cake priced at $2 is the primary merchandise and Brownies priced at $12 is the final thing.

How to Sort the Values of a Python Dictionary in Decreasing Order

If you’d like to type the costs in reducing order, you’ll be able to set the not obligatory opposite parameter to True, as defined under.

sorted_desserts = dict(looked after(cakes.pieces(), key=lambda merchandise:merchandise[1], 
opposite=True))
print(sorted_desserts)

# Output
'Brownies': 12, 'Ice cream': 10, 'Swiss roll': 5, 'Cookies': 4, 
'Cheesecake': 3, 'Cup cake': 2

Now, sorted_desserts has been looked after within the reducing order of costs, beginning with the most costly dessert Brownies costing $12.

Wrapping Up 👩🏽‍💻

Let’s temporarily summarize all that we’ve realized on this instructional.

  • A Python dictionary shops knowledge in key-value pairs; the keys must all be distinctive.
  • In the method of sorting a dictionary by key or price, we create a new dictionary this is looked after as wanted.
  • You can use the integrated dictionary strategies, .keys() and .pieces() to retrieve the entire keys and key-value pairs, respectively.
  • You can use the looked after() serve as in conjunction with the not obligatory parameters key and opposite to reach the required sorting.

Now that you just’ve realized how to type a Python dictionary, be informed to type Python lists. Happy coding!🎉

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button