Dictionary
Dictionary
Dictionary in Python is an unordered collection of data, used to store data values along with the keys.
Dictionary holds the key : value pair. We can also refer to a dictionary as a mapping between a set of
keys and a set of values. Each key-value pair in a Dictionary is separated by a colon (:). E.g.
dict={ “a": “alpha", “o": “omega", “g": ”gamma” }
# Creating a Dictionary with Integer Keys Dictionary with the use of Integer
Dict = {1: ‘AAA', 2: ‘BBB', 3: ‘CCC'} Keys:
print("\nDictionary with the use of Integer Keys: ") {1: ‘AAA', 2: ‘BBB', 3: ‘CCC'}
print(Dict)
# Creating a Dictionary with Mixed keys Dictionary with the use of Mixed
Dict = {'Name': ‘Govind', 1: [10, 11, 12, 13]} Keys:
print("\nDictionary with the use of Mixed Keys: ") {'Name': 'Govind', 1: [10, 11, 12, 13]}
print(Dict)
# Creating a Dictionary with dict() method Dictionary with the use of dict():
D=dict({1: 'AAA', 2: 'BBB', 3:'CCC'}) {1: 'AAA', 2: 'BBB', 3: 'CCC'}
print("\nDictionary with the use of dict(): ") Dictionary with each item as a pair:
print(D) {1: 'AAA', 2: 'BBB'}
print("\n all values in the dictionary, one by one:") all values in the dictionary, one by one:
for i in D: AAA BBB CCC
print(D[i], end=' ')
print("\n all keys in the dictionary using keys() all keys in the dictionary using keys()
method:") method:
for i in D.keys(): 123
print(i, end=' ')
print("\n all values in the dictionary using values() all values in the dictionary using
method:") values() method:
for i in D.values(): AAA BBB CCC
print(i, end=' ')
print("\n all keys and values in the dictionary using all keys and values in the dictionary
items()method:") using items()method:
for k, v in D.items(): 1 AAA 2 BBB 3 CCC
print(k, v, end=' ')
64
Built-in functions in dictionary:-
dict() :- dict() function creates a D = dict(name = "Aman", age = 36, country = "India")
dictionary. print(D)
Output:-{'name': 'Aman', 'age': 36, 'country': 'India'}
keys():- returns all the available keys D = dict(name = "Aman", age = 36, country = "India")
print(D.keys())
Output: dict_keys(['name', 'age', 'country'])
values()-returns all the available D = dict(name = "Aman", age = 36, country = "India")
values print(D.values( ))
Output:dict_values(['Aman', 36, 'India'])
65
pop() : method removes the specified D={1:'AAA', 2:'BBB', 3:'CCC'}
item from the dictionary and return print(D.pop(2))
the corresponding value Output : ’BBB’
MIND MAP
MCQ
1. What is the syntax to create an empty dictionary in Python?
a) dict = {}
b) dict = []
c) dict = ()
d) dict = None
Answer: a) dict = {}
66
2. Which method is used to add a new key-value pair to a dictionary?
a) append()
b) update()
c) insert()
d) add()
Answer: b) update()
4. What happens if you try to access a key that doesn't exist in a dictionary?
a) It returns None
b) It raises a KeyError
c) It returns an empty string
d) It returns 0
Answer: b) It raises a KeyError
8. Which method is used to add new key value pair if not exists ?
a) get()
b) setdefault()
c) add()
d) insert()
Answer: a) setdefault()
2. Create a dictionary to store student information, including name, age, and grade. Write a function
to add a new student and another function to retrieve a student's information by name.
3. Given a dictionary of student grades, write a function to calculate the average grade for each
student and return the result in a new dictionary.
Input: {"John": [80, 70, 90], "Jane": [90, 80, 70]}
Output: {"John": 80.0, "Jane": 80.0}
5. Create a dictionary to store book information, including title, author, and price. Write a function to
find the average price of books by a specific author.
6. Given a dictionary of employee data, write a function to find the highest salary and return the
employee's name and salary.
Input: {"John": 50000, "Jane": 60000, "Bob": 70000}
Output: ("Bob", 70000)
7. Write a function to remove duplicate values from a dictionary and return the result.
Input: {"a": 1, "b": 2, "c": 1, "d": 3}
Output: {"a": 1, "b": 2, "d": 3}
8. Create a dictionary to store city information, including name, population, and country.
9. With respect to Q. 8 , Write a function to find cities with a population greater than a given
threshold.
10. Write a small project using the concept learnt so far.