Dictionary comprehension in Python

 Dictionary comprehension in Python


Dictionary comprehension is a way to create a dictionary using a concise syntax. It allows you to define a dictionary using a single line of code, without having to write a for loop or use the dict() constructor. Here's an example of creating a dictionary using dictionary comprehension:


python


squares = {x: x**2 for x in range(1, 6)}

print(squares)

In this example, we define a dictionary squares using dictionary comprehension, where the keys are numbers from 1 to 5, and the values are the squares of those numbers. We use the range function to generate the keys, and the ** operator to calculate the values.


You can also use dictionary comprehension to filter the items in a dictionary. Here's an example of creating a new dictionary that only contains even numbers from an existing dictionary:


python


numbers = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5}

evens = {k: v for k, v in numbers.items() if v % 2 == 0}

print(evens)

In this example, we define a dictionary numbers with some elements, and use dictionary comprehension 

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...