Python dictionary comprehensions are a powerful way to create and manipulate dictionaries in a concise and efficient way. With this technique, you can write complex code in a single line and perform operations on dictionary keys and values without having to write multiple lines of code. Here are ten examples to help you master dictionary comprehensions in Python:
- Create a dictionary with keys from a list and values initialized to zero:
cssCopy codemy_list = ['a', 'b', 'c'] my_dict = {key: 0 for key in my_list} print(my_dict) # Output: {'a': 0, 'b': 0, 'c': 0}
- Create a dictionary with keys from a list and values from a range:
cssCopy codemy_list = ['a', 'b', 'c'] my_dict = {key: i for i, key in enumerate(my_list)} print(my_dict) # Output: {'a': 0, 'b': 1, 'c': 2}
- Create a dictionary from two lists of the same length:
cssCopy codekeys = ['a', 'b', 'c'] values = [1, 2, 3] my_dict = {keys[i]: values[i] for i in range(len(keys))} print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
- Create a dictionary with keys from a list and values from a function:
pythonCopy codedef square(x): return x ** 2 my_list = [1, 2, 3] my_dict = {key: square(key) for key in my_list} print(my_dict) # Output: {1: 1, 2: 4, 3: 9}
- Create a dictionary from a list of tuples:
cssCopy codemy_list = [('a', 1), ('b', 2), ('c', 3)] my_dict = {key: value for key, value in my_list} print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
- Filter a dictionary based on a condition:
cssCopy codemy_dict = {'a': 1, 'b': 2, 'c': 3} my_dict = {key: value for key, value in my_dict.items() if value > 1} print(my_dict) # Output: {'b': 2, 'c': 3}
- Create a dictionary from a list of objects:
cssCopy codeclass Person: def __init__(self, name, age): self.name = name self.age = age people = [Person('Alice', 25), Person('Bob', 30), Person('Charlie', 35)] my_dict = {person.name: person.age for person in people} print(my_dict) # Output: {'Alice': 25, 'Bob': 30, 'Charlie': 35}
- Merge two dictionaries:
cssCopy codedict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} merged_dict = {**dict1, **dict2} print(merged_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
- Create a nested dictionary:
perlCopy codekeys = ['a', 'b', 'c'] values = [1, 2, 3] nested_dict = {key: {'value': value} for key, value in zip(keys, values)}print(nested
Output: {'a': {'value': 1}, 'b': {'value': 2}, 'c': {'value': 3}}
cssCopy code10. Count the frequency of characters in a string and store the result in a dictionary:
my_string = “hello world” char_freq = {char: my_string.count(char) for char in my_string} print(char_freq)