0% found this document useful (0 votes)
3 views

Dictionary

The document provides an overview of Python dictionaries, describing their characteristics, methods for creation, and built-in functions. It includes examples of creating dictionaries, accessing elements, and manipulating key-value pairs. Additionally, it features multiple-choice questions and competency-based tasks related to dictionary usage in Python.

Uploaded by

vermaanita43892
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Dictionary

The document provides an overview of Python dictionaries, describing their characteristics, methods for creation, and built-in functions. It includes examples of creating dictionaries, accessing elements, and manipulating key-value pairs. Additionally, it features multiple-choice questions and competency-based tasks related to dictionary usage in Python.

Uploaded by

vermaanita43892
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

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” }

CHARACTERISTICS OF PYTHON DICTIONARY:


1. The combination of Key and Value is called Key-Value Pair.
2. Keys and their values are separated by colon(:)
3. Different Key-Value pairs are separated by comma(,).
4. Keys are unique for each Value.
5. Keys of dictionary must be of immutable type like string, number etc.

# Creating an empty Dictionary Output


Dict = {} Empty Dictionary:
print("Empty Dictionary: ") {}
print(Dict)

# 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'}

# Adding elements one at a time Dictionary after adding 3 elements:


Dict={} {0: 'Govind', 2: ‘Prasad', 3: ‘Arya’}
Dict[0] = ‘Govind'
Dict[2] = ‘Prasad'
Dict[3] = ‘Arya’
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dictionary after adding set of values:
# Adding set of values {0: 'Govind', 2: ‘Prasad', 3: ‘Arya’ , 'V':
# to a single Key (1, 2,)}
Dict['V'] = 1, 2
63
print("\nDictionary after adding set of values: ")
print(Dict) Updated dictionary:
{0: 'Govind', 2: ‘Prasad', 3: ‘Arya’ , 'V':
# Updating existing Key's Value (3, 4,)}
Dict[‘V’] = 3,4
print("\nUpdated dictionary: ")
print(Dict)
# Creating a Dictionary
D = {1: ‘Prasad', 'name': ‘Govind', 3: ‘Arya'}

# accessing a element using key Output


print("Accessing a element using key:") Accessing a element using key:
print(D['name']) Govind

# accessing a element using key Accessing a element using key:


print("Accessing a element using key:") Prasad
print(D[1])

# accessing a element using get() method Accessing a element using get:


print("Accessing a element using get:") Arya
print(D.get(3))
D={1:'AAA', 2:'BBB', 3:'CCC'} Output
print("\n all key names in the dictionary, one by one:") all key names in the dictionary, one by
for i in D: one:
print(i, end=' ') 123

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:-

Function Example with output

len():- Returns the length of the D={1:'AAA', 2:'BBB', 3:'CCC'}


dictionary print('Length', '=',len(D))
Output:- Length= 3

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'])

items():- returns key:value pair as D={1:'AAA', 2:'BBB', 3:'CCC'}


object for k, v in D.items():
print(k, v, end=’#')
Output: 1 AAA # 2 BBB # 3 CCC

get(): returns the value of the item D={1:'AAA', 2:'BBB', 3:'CCC'}


with specified key print(D.get(2))
Output: BBB

update():- inserts the specified items D={1:'AAA', 2:'BBB', 3:'CCC'}


to the dictionary D.update({4:’DDD’})
print(D)
Output : {1: 'AAA', 2: 'BBB', 3: 'CCC',4:’DDD’}

del() – used to delete the key:value D={1:'AAA', 2:'BBB', 3:'CCC', 4:’DDD’ }


pair D.del(2)
print(D)
Output : {1: 'AAA', 3: 'CCC',4:’DDD’}

clear() – removes all elements from D={1:'AAA', 2:'BBB', 3:'CCC'}


the dictionary D.clear()
print(D)
Output : {}

fromKeys() : creates a new dictionary D=(1,2,3)


from the given sequence of elements print(dict.fromkeys(D,None))
with a value provided by the user. Output : {1: None, 3: None,4:None}

copy() : to make a copy of the D={1:'AAA', 2:'BBB', 3:'CCC'}


dictionary D1=D.copy()
print(D1)
Output : {1: 'AAA', 3: 'CCC',4:’DDD’}

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’

popitem() : Remove the last item from D={1:'AAA', 2:'BBB', 3:'CCC'}


the dictionary print(D.popitem())
Output : 3: ’CCC’

setdefault() : This method inserts a new D={1:'AAA', 2:'BBB', 3:'CCC'}


key: value pair only if the key does not print(D.setdefault(4,200))
exist and If the key already exists, it returns Output : 200
the current value in both cases. D now is {1: 'AAA', 2: 'BBB', 3: 'CCC', 4: 200}

max() : returns the maximum key D={1:'AAA', 2:'BBB', 3:'CCC'}


value print(max(D))
Output : 3

min() : returns the minimum key value D={1:'AAA', 2:'BBB', 3:'CCC'}


print(min(D))
Output : 1

sorted(): returns the dictionary in D={10:'AAA', 2:'BBB', 3:'CCC'}


sorted order on keys/values print(sorted(D.items()))
print(sorted(D.values()))
Output :[(2, 'BBB'), (3, 'CCC'), (10, 'AAA')]
['AAA', 'BBB', 'CCC']

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()

3. How do you access the value of a key in a dictionary?


a) dict[key]
b) dict.key
c) dict.get(key)
d) dict[key][ ]
Answer: a) dict[key]

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

5. Which method is used to remove a key-value pair from a dictionary?


a) pop()
b) remove()
c) delete()
d) clear()
Answer: a) pop()

6. How do you iterate over the key-value pairs of a dictionary?


a) for key in dict:
b) for key, value in dict.items():
c) for key, value in dict:
d) for key in dict.keys():
Answer: b) for key, value in dict.items():

7. What is the output of dict.keys()?


a) A list of keys
b) A list of values
c) A list of key-value pairs
d) A dictionary
Answer: a) A list of keys

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()

9. How do you merge two dictionaries?


67
a) dict1 + dict2
b) dict1.update(dict2)
c) dict1.merge(dict2)
d) dict1.extend(dict2)
Answer: b) dict1.update(dict2)

10. What is the output of dict.clear()?


a) An empty dictionary
b) A dictionary with one key-value pair
c) A dictionary with all keys removed
d) A dictionary with all values removed
Answer: a) An empty dictionary

COMPETENCY BASED QUESTIONS


1. Write a Python function to count the frequency of each word in a given string and store the result
in a dictionary.
e.g.
Input: "Hello world, hello python"
Output: {"Hello": 2, "world": 1, "python": 1}

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}

4. Write a function to merge two dictionaries and return the result.


Input: dict1 = {"a": 1, "b": 2}, dict2 = {"c": 3, "d": 4}
Output: {"a": 1, "b": 2, "c": 3, "d": 4}

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.

VERY SHORT QUESTIONS


1. What is the syntax to create an empty dictionary? - {} or dict()
2. How do you add a key-value pair to a dictionary? - dict[key] = value
68

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy