2.3 - Samad
2.3 - Samad
WORKSHEET 2.3
AIM: Program to demonstrate creation and accessing of dictionary and apply different kinds of
operations on them.
Python Dictionaries:
Each key is separated from its value by a colon (:), the items are separated by commas, and the
whole thing is enclosed in curly braces. An empty dictionary without any items is written with
just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be
of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
1. Write a Python program to combine two dictionary adding values for common keys.
d1 = {'a': 100, 'b': 200, 'c':300},d2 = {'a': 300, 'b': 200, 'd':400}
d3[key] = d1[key]
Output:
# Method 1
sum_of_values = sum(my_dict.values())
print("Sum of all values in the dictionary: ", sum_of_values)
# Method 2 sum_of_values =
0 for value in my_dict.values():
sum_of_values += value
Output:
3. Write a Python program to get the maximum and minimum values of a dictionary.
Output:
# Method 1
product_of_values = 1 for value in
my_dict.values():
product_of_values *= value
print("Product of all values in the dictionary: ", product_of_values)
Output:
5. Write a Python program to find the highest 3 values of corresponding keys in a dictionary.
Output:
6. Write a Python script to concatenate the following dictionaries to create a new one. Sample
Dictionary : dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60}.
# Method 1
concatenated_dict = {**dic1, **dic2, **dic3} print("Concatenated dictionary:
", concatenated_dict)
# Method 2
concatenated_dict = {} for d
in [dic1, dic2, dic3]:
concatenated_dict.update(d) print("Concatenated
dictionary: ", concatenated_dict)
Output: