Python Tutorial

Python Flow Control

Python Functions

Python Data Types

Python Date and Time

Python Files

Python String

Python List

Python Dictionary

Python Variable

Python Input/Output

Python Exceptions

Python Advanced

How to create dictionary with dict comprehension and iterables in Python

Dictionary comprehension is a concise way to create dictionaries in Python using a single line of code. It is similar to list comprehension but creates dictionaries instead of lists. In this tutorial, we will discuss how to create a dictionary using dictionary comprehension with iterables in Python.

  • Using dictionary comprehension with two iterables:

If you have two iterables (e.g., lists or tuples), one for keys and another for values, you can use the zip() function along with dictionary comprehension to create a dictionary.

Example:

keys = ['a', 'b', 'c', 'd']
values = [1, 2, 3, 4]

my_dict = {k: v for k, v in zip(keys, values)}
print(my_dict)

Output:

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

In this example, the zip() function is used to combine the keys and values iterables into pairs. Then, dictionary comprehension is used to create a dictionary with keys and values from these pairs.

  • Using dictionary comprehension with a single iterable:

If you have a single iterable and want to create a dictionary where the keys are the elements of the iterable, and the values are derived from a function or expression, you can use dictionary comprehension directly.

Example:

words = ["apple", "banana", "cherry", "date"]

word_length_dict = {word: len(word) for word in words}
print(word_length_dict)

Output:

{'apple': 5, 'banana': 6, 'cherry': 6, 'date': 4}

In this example, dictionary comprehension is used to create a dictionary where the keys are the elements of the words list, and the values are the lengths of the words.

  • Using dictionary comprehension with a condition:

You can also add a condition in the dictionary comprehension to create a dictionary based on specific criteria.

Example:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

even_square_dict = {n: n**2 for n in numbers if n % 2 == 0}
print(even_square_dict)

Output:

{2: 4, 4: 16, 6: 36, 8: 64}

In this example, the dictionary comprehension is used to create a dictionary where the keys are the even numbers in the numbers list, and the values are the squares of those even numbers.

In conclusion, dictionary comprehension is a concise and efficient way to create dictionaries in Python. You can use it with one or more iterables to create dictionaries based on keys, values, and conditions.

  1. Creating dictionaries from lists with dict comprehension:

    • Description: Dictionary comprehension allows creating dictionaries by specifying key-value pairs based on an iterable.
    • Code:
    numbers = [1, 2, 3, 4, 5]
    squared_dict = {num: num**2 for num in numbers}
    
  2. Using conditionals in dictionary comprehension in Python:

    • Description: Conditional expressions can be used in dictionary comprehension to filter or modify key-value pairs.
    • Code:
    numbers = [1, 2, 3, 4, 5]
    even_squared_dict = {num: num**2 for num in numbers if num % 2 == 0}
    
  3. Transforming iterables into dictionaries with dict comprehension:

    • Description: Any iterable can be used to create a dictionary by specifying how to derive keys and values.
    • Code:
    names = ["Alice", "Bob", "Charlie"]
    name_lengths = {name: len(name) for name in names}
    
  4. Nested dictionary comprehension in Python:

    • Description: Dictionary comprehension can be nested to create dictionaries with nested structures.
    • Code:
    matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    flattened_dict = {(i, j): matrix[i][j] for i in range(3) for j in range(3)}
    
  5. Combining multiple iterables in dictionary comprehension:

    • Description: Multiple iterables can be zipped together to create key-value pairs in the dictionary comprehension.
    • Code:
    names = ["Alice", "Bob", "Charlie"]
    ages = [25, 30, 35]
    person_dict = {name: age for name, age in zip(names, ages)}
    
  6. Filtering and mapping values in dictionary comprehension:

    • Description: Values in the dictionary can be filtered or transformed using conditions and expressions.
    • Code:
    numbers = [1, 2, 3, 4, 5]
    squared_even_dict = {num: num**2 if num % 2 == 0 else None for num in numbers}
    
  7. Working with keys and values in Python dictionary comprehension:

    • Description: Key and value can be manipulated in the comprehension to create desired key-value pairs.
    • Code:
    numbers = [1, 2, 3, 4, 5]
    squared_minus_one_dict = {num: num**2 - 1 for num in numbers}
    
  8. Converting tuples or sets to dictionaries with dict comprehension:

    • Description: Tuples or sets can be used to create key-value pairs in a dictionary using comprehension.
    • Code:
    coordinates = {(x, x**2) for x in range(5)}
    coord_dict = {k: v for k, v in coordinates}