top of page

Python Dictionary Tricks That Make Your Code Elegant

Updated: Jan 28, 2023

This article will introduce the dictionary operation tricks that are used by senior python engineers.


  1. UNION operator to merge dictionaries. we can write for loops to combine the elements of different dictionaries. But Since Python 3.9, we never need to do it manually.

You can also make an in-place update using |=

2. unpacking dictionaries with asterisks. Due to its simplicity, we can always use the union operator it its possible. We can use the dictionary unpacking trick instead of union, to get the same results.

3. Dictionary comprehension to create dictionaries. Like list comprehension in python the dict comprehension, which is an elegant way to create dictionaries, gives us the flexibility to filter our data, since it can contain the if statement.


syntax:

dict_1 = {key:value for key, value in iterable (if condition)}


The following example, which leverages the power of dict comprehensions, generates a dict from two lists in one line of code:

4. Reversing Keys and Values of a Dictionary. We have different ways to reverse the Key/Value as Value/Key in the dictionary.

5. Converting a list of tuples into dictionary. If the list contains (Kye, Value) tuples, we can convert into dictionary.

6. Sorting a dictionary using value:

7. using defaultdict, when you get the value of a dict by non-existing key, an exception will be raised.

To avoid unexpected issues, a good solution is to use the defaultdict. defaultdict is a sub-class of the dictionary class that returns a dictionary-like object. The functionality of both dictionary and defaultdict are almost same, except for the fact that defaultdict never raises a KeyError. It provides a default value for the key that does not exist.

Another simplest way to avoid unexpected issues, use the get () method.

8. using Counter, collections module Counter function will calculate each letter, how many times repeated in a string, and returns the result as a dictionary.


 

Thanks for reading!!!


Your Rating and Review will be appreciated!!


Twitter: @LearnerLandmark

Recent Posts

See All

Comentarios

Obtuvo 0 de 5 estrellas.
Aún no hay calificaciones

Los comentarios se han desactivado.
bottom of page