Thursday, August 31, 2023
HomeProgrammingMaking a Dictionary with Comprehension in Python

Making a Dictionary with Comprehension in Python


Introduction

As you have most likely come to be taught with Python, there are fairly a number of methods to do an operation, some strategies being higher than others. One of many options that contribute to its energy is the flexibility to create dictionaries utilizing dictionary comprehension. This Byte will introduce you to this idea and show the way it could make your code extra environment friendly and readable.

Why Use Dictionary Comprehension?

Dictionary comprehension is a concise and memory-efficient solution to create and populate dictionaries in Python. It follows the precept of “Do extra with much less code”. It is not nearly writing much less code, it is also about making the code extra readable and simpler to know.

Take into account a state of affairs the place it’s essential to create a dictionary from an inventory. With out dictionary comprehension, you would wish to create an empty dictionary after which use a for loop so as to add parts to it. With dictionary comprehension, you are able to do this in a single line of code, as we’ll see later.

Intro to Listing Comprehension

Earlier than we dive into dictionary comprehension, let’s first perceive listing comprehension. Listing comprehension is a syntactic assemble accessible in Python for creating an inventory from current lists. It follows the type of the mathematical set-builder notation (set comprehension).

Here is an instance:

# With out listing comprehension
numbers = [1, 2, 3, 4, 5]
squares = []
for n in numbers:
    squares.append(n**2)
print(squares)  # [1, 4, 9, 16, 25]

# With listing comprehension
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]
print(squares)  # [1, 4, 9, 16, 25]

As you may see, listing comprehension means that you can create lists in a really concise method.

Hyperlink: For a deeper dive into listing comprehension, take a look at our information, Listing Comprehensions in Python.

Changing Listing Comprehension to Dictionary Comprehension

Now that you simply perceive listing comprehension, changing it to dictionary comprehension is fairly easy. The principle distinction is that whereas listing comprehension outputs an inventory, dictionary comprehension outputs a dictionary, clearly 😉.

To transform an inventory comprehension to a dictionary comprehension, it’s essential to change the brackets [] to braces {}, and add a key earlier than the colon :.

Let’s have a look at what this might appear like:

# Listing comprehension
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]
print(squares)  # [1, 4, 9, 16, 25]

# Dictionary comprehension
numbers = [1, 2, 3, 4, 5]
squares = {n: n**2 for n in numbers}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Within the dictionary comprehension, n is the important thing and n**2 is the worth. The comprehension iterates over the numbers listing, assigns every quantity to n, after which provides n as a key and n**2 as a worth to the squares dictionary.

Easy Examples of Dictionary Comprehension

Dictionary comprehension in Python is an environment friendly solution to create dictionaries. It is a concise syntax that reduces the quantity of code it’s essential to write. Let’s begin with a easy instance.

# Making a dictionary of squares for numbers from 0 to five
squares = {num: num**2 for num in vary(6)}
print(squares)

Output:

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

On this instance, the expression num: num**2 is the key-value pair of the brand new dictionary. The for num in vary(6) is the context of the dictionary comprehension, specifying the vary of numbers to incorporate within the dictionary.

Superior Dictionary Comprehension

You may as well use dictionary comprehension for extra advanced operations. Let’s check out a case the place we create a dictionary from an inventory of phrases, with the phrases as keys and their lengths as values.

phrases = ["Python", "comprehension", "dictionary", "example"]
word_lengths = {phrase: len(phrase) for phrase in phrases}
print(word_lengths)

Output:

{'Python': 6, 'comprehension': 13, 'dictionary': 10, 'instance': 7}

The expression phrase: len(phrase) generates the key-value pairs. The for phrase in phrases gives the context, iterating over every phrase within the listing.

Conclusion

Dictionary comprehension in Python affords a concise and environment friendly solution to create dictionaries. By understanding tips on how to use it correctly, you may write cleaner, extra environment friendly code. As with all device, the important thing to utilizing this successfully is knowing its strengths and limitations.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments