Quick actions

cmd+k|ctrl+k

Navigation

Languages

dict_comp

Snippet info

Language

Python

Visibility

public

Author

aaron.lung.wai

Created

2025-12-09T03:43:58.096852Z

Updated

2025-12-09T03:43:58.096852Z

1. Squares Dictionary
Create a dictionary where keys are numbers 1-5, and values are their squares.
Input: None → Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

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

2. Even-Odd Classifier
Classify numbers 1-10 as 'even' or 'odd'.
Output: {1: 'odd', 2: 'even', ..., 10: 'even'}
#result = "odd" if x % 2 else 'even'
even_odd = {x: 'odd' if x % 2  else 'even' for x in range(1, 11)}

3. Word Length Mapping
Map words to their lengths.
Input  : ['apple', 'cat', 'python'] → Output: {'apple': 5, 'cat': 3, 'python': 6}

words = ['apple', 'cat', 'python']
lengths = {word: len(word) for word in words}

4. List to Dictionary
Convert a list into a dictionary with indices as keys.
Input: ['a', 'b', 'c'] → Output: {0: 'a', 1: 'b', 2: 'c'}
 {i: li[i] for i in range(len(li))}
lst = ['a', 'b', 'c']
dict_from_list = {i: v for i, v in enumerate(lst)}

5. Uppercase Keys
Create a dictionary with keys as uppercase versions of input strings.
Input: ['apple', 'banana'] → Output: {'APPLE': 'apple', 'BANANA': 'banana'}

fruits = ['apple', 'banana']
upper_dict = {fruit.upper(): fruit for fruit in fruits}

6. Filter by Value
Keep key-value pairs where the value is divisible by 3.
Input dict1 : {'a': 9, 'b': 4, 'c': 12} → Output: {'a': 9, 'c': 12}
 {k: v  for k,v in dict1.items() if  v % 3 == 0}
d = {'a': 9, 'b': 4, 'c': 12}
filtered = {k: v for k, v in d.items() if v % 3 == 0}

7. Merge Lists into Dict
Combine two lists into a dictionary.
Input: keys = ['a', 'b'], values = [1, 2] → Output: {'a': 1, 'b': 2}

keys = ['a', 'b']
values = [1, 2]
merged = {k: v for k, v in zip(keys, values)}

8. Character Count
Count occurrences of each character in a string.
Input: 'hello' → Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}

s = 'hello'
count = {char: s.count(char) for char in s}

9. Invert Mapping
Swap keys and values in a dictionary.
Input: {'a': 1, 'b': 2} → Output: {1: 'a', 2: 'b'}

original = {'a': 1, 'b': 2}
inverted = {v: k for k, v in original.items()}

10. Prime Check Dictionary
Create a dictionary mapping numbers 1-10 to True/False for primes.
Output: {1: False, 2: True, 3: True, ..., 10: False}

def is_prime(n):
    if n < 2: return False
    for i in range(2, int(n**0.5)+1):
        if n % i == 0: return False
    return True

prime_check = {x: is_prime(x) for x in range(1, 11)}

11. Type-Based Keys
Map variables to their data types.
Input: [10, 'hello', 3.14, True] → Output: {10: int, 'hello': str, 3.14: float, True: bool}

variables = [10, 'hello', 3.14, True]
type_dict = {var: type(var) for var in variables}


12. Nested Dictionary Comprehension
Create a dictionary where keys are numbers 1-3, and values are lists of their multiples up to 10.
Output: {1: [1,2,3,4,5,6,7,8,9,10], 2: [2,4,6,8,10], 3: [3,6,9]}


multiples = {n: [n*i for i in range(1, 11) if n*i <= 10] for n in range(1, 4)}

13. Remove Vowels (Advanced)
Map non-vowel characters to their indices in a string.
Input: 'hello' → Output: {0: 'h', 2: 'l', 3: 'l'}

s = 'hello'
no_vowels = {i: s[i] for i in range(len(s)) if s[i].lower() not in 'aeiou'}

14. Common Elements in Two Dictionaries
Create a dictionary of key-value pairs present in both dictionaries.
Input: dict1 = {'a': 1, 'b': 2}, dict2 = {'b': 2, 'c': 3} → Output: {'b': 2}

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 2, 'c': 3}
common = {k: v for k, v in dict1.items() if k in dict2 and dict2[k] == v}

15. Matrix to Dictionary
Convert a matrix to a dictionary with coordinates as keys.
Input: [[1, 2], [3, 4]] → Output: {(0,0): 1, (0,1): 2, (1,0): 3, (1,1): 4}

matrix = [[1, 2], [3, 4]]
coord_dict = {(i, j): matrix[i][j] for i in range(len(matrix)) for j in range(len(matrix[0]))}

16. Factorial Dictionary
Map numbers 1-5 to their factorials.
Output: {1: 1, 2: 2, 3: 6, 4: 24, 5: 120}

import math
factorials = {n: math.factorial(n) for n in range(1, 6)}

17. ASCII Value Mapping
Map characters to their ASCII values.
Input: 'abc' → Output: {'a': 97, 'b': 98, 'c': 99}

s = 'abc'
ascii_dict = {char: ord(char) for char in s}

18. Conditional Summation
Sum values of keys starting with 'a'.
Input: {'apple': 3, 'banana': 5, 'apricot': 7} → Output: 10

d = {'apple': 3, 'banana': 5, 'apricot': 7}
total = sum(v for k, v in d.items() if k.startswith('a'))

19. Flatten List Indices
Map indices of a flattened nested list to their values.
Input: [[1, 2], [3, 4]] → Output: {0: 1, 1: 2, 2: 3, 3: 4}

nested = [[1, 2], [3, 4]]
flat_indices = {i: val for i, val in enumerate([num for sublist in nested for num in sublist])}

20. Word Frequency Dictionary
Count word frequencies while preserving insertion order (Python 3.7+).
Input: 'apple banana apple cherry' → Output: {'apple': 2, 'banana': 1, 'cherry': 1}


s = 'apple banana apple cherry'
words = s.split()
freq = {word: words.count(word) for word in words if word not in freq}  # Requires Python 3.8+ walrus operator
# Alternative (works in all versions):
freq = {}
{freq.setdefault(word, words.count(word)) for word in words}
INFO