Dictionaries Exercises#
Question-1#
Create a dictionary with the pairs: (‘Banana’, 100), (‘Cherry’,20), (‘Apple’,200), (‘Pear’,75 ) which corresponds to fruit inventory of a market in the form of name and number of boxes of the fruits. Perform the following operations on it, printing it after each operation:
Add a new pair (‘Strawberry’, 130).
Add all pairs in the following dictionary: (‘Peach’,90),(‘Pineapple’,40) .
Remove the pair of Pear.
Verify if ‘Peach’ is a key in the dictionary.
Verify if ‘Orange’ is not a key in the dictionary.
Verify if 75 is a value in the dictionary.
Print the number of pairs in the dictionary.
Print the sum of values in the dictionary.
Print the maximum value in the dictionary.
Print the minimum value in the dictionary.
Question-2#
Create a list containing the keys from the provided dictionary, where the corresponding values are even numbers.
state_num = {'NY':135, 'TX':236, 'FL':207, 'CA':140, 'NJ':98, 'MO':175, 'AZ':124}
Question-3#
Create a new dictionary with the same keys as the “grades” dictionary, but with the values being the average of the test scores for each student.
grades = {'Jack':[100,90,95], 'Ashley':[85,90,95], 'Frank':[100,100,70]}
Question-4#
Generate a list using list comprehension containing the ID numbers from the per_info dictionary.
Compare the length of the generated list with the number of pairs in the per_info dictionary to verify if all ID numbers are unique.
per_info = {'Tom': {'ID':156, 'Age':24, 'Gender':'M', 'State':'NJ'},
'Liz': {'ID':179, 'Age':27, 'Gender':'F', 'State':'AZ'},
'Joe': {'ID':102, 'Age':21, 'Gender':'M', 'State':'TX'},
'Bob': {'ID':101, 'Age':29, 'Gender':'M', 'State':'FL'},
'Eli': {'ID':198, 'Age':26, 'Gender':'F', 'State':'CA'},
'Ian': {'ID':129, 'Age':27, 'Gender':'M', 'State':'NY'},
'Amy': {'ID':145, 'Age':24, 'Gender':'F', 'State':'NY'},
}
Question-5#
If the current year is 2020, calculate the birth year of each person from the per_info dictionary and add the key-value pair ‘Birth year’: birth_year to the dictionary for each person.
Question-6#
Generate a dictionary containing two key-value pairs representing the gender type and the number of persons belonging to that type. Plot a bar chart to visually represent the keys and their corresponding values.
Business Applications#
Portfolio Analysis#
The percentage distribution of investments in a portfolio is represented by the following dictionary:
dist_invest = {'stocks':0.25, 'bonds':0.45, 'cash': 0.10, 'cryptocurrency': 0.05, 'real estate': 0.15}
Write a function that takes the total investment amount as a parameter and returns a dictionary where the keys are the investment categories from the dist_invest dictionary, and the values are the corresponding amounts invested in each category.