How to Sort a Python Dictionary by Key or Value

On this tutorial you’ll discover ways to type a Python dictionary by key or worth.

When working with a dictionary in Python, there are occasions when you want to type its contents: by key or by worth. As a result of a Python dictionary is a key-value mapping, create a brand new dictionary with the keys or values ​​sorted as wanted.

On this tutorial, we’ll begin by going over the fundamentals of the Python dictionary. Subsequent, we discover ways to create a brand new dictionary during which the contents are sorted by key or by worth, if needed.

Fundamentals of Python Dictionary, Revisited

What’s a Python dictionary?

Dictionary is a built-in knowledge construction in Python. It saves objects as key-value pairs. With the keys you’ll be able to lookup the corresponding values. As a result of the keys uniquely establish the values, there needs to be no duplication of keys.

py_dict = {"Python":"cool!","Study":True}
py_dict["Python"]
# Output: cool!

py_dict["Learn"]
# Output: True

Functionally, a dictionary is just like a hash map. Due to this fact, it’s not essentially an ordered knowledge construction. You possibly can entry the contents of a dictionary in any order, so long as you recognize the keys.

Set up objects in a dictionary

In earlier variations of Python, you had to make use of an OrderedDict to protect the order of the keys. Nonetheless, as of Python 3.7, you’ll be able to entry the objects within the the identical order during which you add them to the dictionary.

Now that you’ve got realized the fundamentals of Python dictionaries, let’s discover ways to create sorted copies of the dictionary.

⚙️ Comment: You want Python 3.7 or increased for the code on this tutorial to work as anticipated. You possibly can obtain the newest model of Python or run the examples within the Geekflare On-line Python Editor.

How one can type a Python dictionary by key

Take a look at the next picture of the dessert menu in a restaurant. There are two columns that correspond to the objects on the menu and their respective costs.

python-dictionary-of-data

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

Let’s go forward and create the dictionary dessertsas proven under.

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

Subsequent, let’s create a dictionary sorted_desserts, with the desserts organized in alphabetical order. Within the authentic desserts dictionary, the names of the desserts are the keys. So type these keys in alphabetical order to create a brand new dictionary.

How one can entry the keys of a Python dictionary

To do that, we first retrieve the keys from the dictionary after which type them in alphabetical order.

In Python you should use the built-in dictionary methodology .keys() to get an inventory of all keys within the dictionary.

Let’s the .keys() methodology on the dessert dictionary to retrieve the keys as proven under.

keys = desserts.keys()
print(keys)

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

Calling the built-in Python sorted() perform with an inventory, for the reason that argument returns a brand new sorted record.

Subsequent, let’s do the sorted() perform with the record keys as an argument and retailer the sorted record within the variable sorted_keys.

sorted_keys = sorted(keys)
print(sorted_keys)

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

Now that we have sorted the keys in alphabetical order, we will lookup the values ​​that match the keys in sorted_keys of the desserts dictionary, as proven under.

sorted_desserts = {}
for key in sorted_keys:
  sorted_desserts[key] = desserts[key]

print(sorted_desserts)

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

Let’s lengthen the code block above:

  • Initialize sorted_desserts be an empty Python dictionary.
  • Stroll by means of the important thing record sorted_keys.
  • For each key sorted_keysadd an merchandise to sorted_desserts by wanting up the corresponding worth within the desserts dictionary.

The habits for Such a loop is taken into account intensive. In Python there’s a extra concise various that makes use of dictionary comprehension.

Dictionary comprehension in Python

Python helps the usage of dictionary comprehension, just like comprehension of lists. Dictionary comprehension means that you can create a brand new Python dictionary with only one line of code.

▶️ Right here is the overall development to make use of dictionary comprehension in Python.

# 1. when you've gotten each keys and values in two lists: list1, list2
new_dict = {key:worth for key,worth in zip(list1,list2)}

# 2. when you've gotten the keys, and might lookup the values
new_dict = {key:worth for key in <iterable>}

Let’s use the second development within the cell above: new_dict = {key:worth for key in <iterable>} to create one sorted_desserts dictionary.

On this instance:

  • iterable: the record sorted_keys
  • key: the important thing we will entry by going by means of sorted_keys
  • worth: lookup the worth that corresponds to the important thing from the dessert dictionary, desserts[key]

All issues thought-about, now we have the expression for dictionary comprehension as proven under.

sorted_desserts = {key:desserts[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 desserts are organized in alphabetical order within the sorted_desserts dictionary.

How one can type a Python dictionary by worth

Subsequent, we discover ways to type a Python dictionary by values.

Within the desserts dictionary, the values ​​correspond to the costs of the desserts. You might need to type the dictionary by worth, in ascending or descending order.

▶️ You should utilize the built-in dictionary methodology .objects() to retrieve all key-value pairs. Every tuple is a key-value pair.

desserts.objects()

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

Every of the objects is a tuple of its personal. So you may as well index into every key-value pair to entry the keys and values ​​individually.

dict_items = desserts.objects()
for merchandise in dict_items:
  print(f"key:{merchandise[0]},worth:{merchandise[1]}")

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

Since we need to type by values, we use the tactic above to get the worth at index 1 within the key-value pair.

How one can type the values ​​of a Python dictionary in ascending order

This time we use the sorted() perform together with the elective key parameter. key will be any Python perform, a built-in perform, a user-defined perform, or perhaps a lambda perform.

Comment: lambda args: expression is the syntax for outlining lambda features in Python.

On this instance of sorting desserts by worth, now we have entry to dictionary entries (key-value pairs). We’re going to sit key = lambda merchandise:merchandise[1] as a result of we need to type by worth (worth).

If sorted() perform returns an inventory by default, you need to explicitly put it in a dictas proven under.

sorted_desserts = dict(sorted(desserts.objects(), key=lambda merchandise:merchandise[1]))
print(sorted_desserts)

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

It’s also possible to rewrite utilizing dictionary comprehension, as mentioned earlier.

sorted_desserts = {key:worth for key, worth in sorted(desserts.objects(), 
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 merchandise.

How one can type the values ​​of a Python dictionary in descending order

To type the costs in descending order, you’ll be able to set the elective Reverse parameter to Trueas defined under.

sorted_desserts = dict(sorted(desserts.objects(), key=lambda merchandise:merchandise[1], 
reverse=True))
print(sorted_desserts)

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

Now, sorted_desserts is sorted in descending worth order, beginning with the most costly dessert Brownies prices $12.

Completion 👩🏽‍💻

Let’s shortly recap the whole lot we realized on this tutorial.

  • A Python dictionary shops knowledge in key-value pairs; the keys should all be distinctive.
  • Whereas sorting a dictionary by key or worth, we create a brand new dictionary that kinds as wanted.
  • You should utilize the built-in dictionary strategies, .Keys() And .objects() to retrieve all keys and key-value pairs, respectively.
  • You should utilize the sorted() perform along with the elective parameters key And backwards to attain the specified type.

Now that you’ve got realized easy methods to type a Python dictionary, you may additionally discover ways to type Python lists. Glad coding!🎉

Leave a Comment

porno izle altyazılı porno porno