-
Notifications
You must be signed in to change notification settings - Fork 2
Dictionary QNA
Ans: Below are 10 Python code questions related to dictionary comprehension along with their answers. Feel free to use them for practice:
Write a dictionary comprehension to create a dictionary of squares for numbers from 1 to 10.
Answer 1:
squares_dict = {num: num**2 for num in range(1, 11)}
print(squares_dict)
Create a dictionary using dictionary comprehension to store the length of each word in a list.
Answer 2:
words = ["apple", "banana", "cherry", "date"]
word_lengths = {word: len(word) for word in words}
print(word_lengths)
Write a dictionary comprehension to filter out odd numbers from a given dictionary.
Answer 3:
numbers_dict = {num: num**2 for num in range(1, 11)}
even_squares_dict = {key: value for key, value in numbers_dict.items() if value % 2 == 0}
print(even_squares_dict)
Create a dictionary comprehension to convert keys to uppercase in a given dictionary.
Answer 4:
original_dict = {"apple": 1, "banana": 2, "cherry": 3}
uppercase_keys_dict = {key.upper(): value for key, value in original_dict.items()}
print(uppercase_keys_dict)
Write a dictionary comprehension to get the count of each character in a given string.
Answer 5:
text = "hello world"
char_count = {char: text.count(char) for char in set(text)}
print(char_count)
Create a dictionary comprehension to filter out items with values less than 5 from a dictionary.
Answer 6:
original_dict = {"a": 3, "b": 7, "c": 2, "d": 9}
filtered_dict = {key: value for key, value in original_dict.items() if value >= 5}
print(filtered_dict)
Write a dictionary comprehension to merge two dictionaries.
Answer 7:
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged_dict = {key: value for d in [dict1, dict2] for key, value in d.items()}
print(merged_dict)
Create a dictionary comprehension to extract even numbers from a list and store their squares.
Answer 8:
numbers_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_squares_dict = {num: num**2 for num in numbers_list if num % 2 == 0}
print(even_squares_dict)
Write a dictionary comprehension to extract vowels from a given string and count their occurrences.
Answer 9:
text = "hello world"
vowel_count = {char: text.count(char) for char in text if char.lower() in "aeiou"}
print(vowel_count)
Create a dictionary comprehension to flatten a list of dictionaries.
Answer 10:
list_of_dicts = [{"a": 1, "b": 2}, {"c": 3, "d": 4}, {"e": 5, "f": 6}]
flattened_dict = {key: value for d in list_of_dicts for key, value in d.items()}
print(flattened_dict)