Python Dictionary Problem-Solving Questions
Basic to Medium Level Questions
1. Frequency Counter
Given a string, count the frequency of each character using a
dictionary.
Example: s = "mississippi" # Expected Output: {'m': 1, 'i': 4,
's': 4, 'p': 2}
2. Swap Keys and Values
Write a program to create a new dictionary in which keys and values of
the dictionary are swapped. Assume that all the values in given
dictionary are unique.
Example: d = {'a': 1, 'b': 2, 'c': 3} # Expected Output: {1: 'a',
2: 'b', 3: 'c'}
3. Find Key with Maximum Value. Also find sum of all values
Find the key in a dictionary with the highest value.
Example: d = {'a': 10, 'b': 50, 'c': 30} # Expected Output: 50,
90
4. Count Words in a Sentence
Write a function to count occurrences of each word in a sentence.
Example: sentence = "this is a test this is only a test" #
Expected Output: {'this': 2, 'is': 2, 'a': 2, 'test': 2, 'only': 1}
5. Nested Dictionary Access
Given a nested dictionary, print the value of the age field.
Example: person = {'name': 'Alice', 'details': {'age': 25,
'city': 'NY'}} #Expected output: 25
6. Dictionary from Two Lists
Convert two lists into a dictionary using inbuilt zip function.
Example: keys = ['a', 'b', 'c'], values = [1, 2, 3] # Output:
{'a': 1, 'b': 2, 'c': 3}
Also, what will be output of the code if the given inputs are keys = [‘s’,
‘i’, ‘v’, ‘a’, ‘y’, ‘y’, ‘a’], values = [‘B’, ‘A’, ‘L’, ‘L’, ‘A’, ‘Y’, ‘A’]
7. Check whether the given input exists as a key in a dictionary without
using the in keyword. If the key exists then print True else False.
8. Filter Dictionary by Condition: Given a list of dictionaries where
each dictionary represents product details (with keys like name, price,
and id), filter and return the products where the name starts with 'a' or
the price is less than 100 and the id is greater than 22.
Example:
1.
2. #Expected output: apple almond berry