0% found this document useful (0 votes)
2 views20 pages

Unit IV Dictionary.ppt

Uploaded by

sanjucrypto1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views20 pages

Unit IV Dictionary.ppt

Uploaded by

sanjucrypto1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Unit 4, Topic 1

Dictionaries
UNIT – IV DICTIONARIES AND FILES (8)

Dictionary: Creating, Accessing, Adding Items, Modifying, T1 366-370


44 1 BB & Demo MCQ C112.3
Deleting T2 103-105

Sorting, Looping, Nested Dictionaries Built-in T1 370-373


45 1 BB & Demo MCQ C112.3
Dictionary Function T2 105-109
T1 374-377
46 Finding Key and Value in a Dictionary 1 BB & Demo MCQ C112.3
T2 109-111
T1 289-291
47 1 BB & Demo MCQ C112.4
Introduction to Files – File Modes T2 137-139
Opening and Closing Files – Reading and Writing
48 T1 292-294 1 BB & Demo MCQ C112.4
Files
Opening and Closing Files – Reading and Writing
49 T1 295-321 1 BB & Demo MCQ C112.4
Files

LAB EXPERIMENTS
Python Programs using Files a)
Write Python script to display file contents. b)
50 7 1 Viva C112.4
Write Python script to copy file contents from one file to
another.
51 Python Programs using Exceptions 8 1 Viva C112.4
• Dictionary in Python is an unordered collection of data values,
used to store data values like a map, which, unlike other data
types that hold only a single value as an element, Dictionary
holds key:value pair. Key-Value is provided in the dictionary to
make it more optimised.
Creating a Dictionary

• In Python, a dictionary can be created by placing a sequence of


elements within curly {} braces, separated by ‘comma’.
Dictionary holds pairs of values, one being the Key and the
other corresponding pair element being its Key:value. Values in
a dictionary can be of any data type and can be duplicated,
whereas keys can’t be repeated and must be immutable.
# Creating a Dictionary with Integer Keys

Dict = {1: ‘God', 2: ‘is', 3: ‘Good'} Output


print("\nDictionary with the use of Integer Keys: ")
print(Dict) Dictionary with the use of Integer Keys:
{1: ‘God', 2: ‘is', 3: ‘Good'}

# Creating a Dictionary with Mixed keys Dictionary with the use of Mixed Keys:
{'Name': ‘God', 1: [1, 2, 3, 4]}

Dict = {'Name': ‘God', 1: [1, 2, 3, 4]}


print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
• Dictionary can also be created by the built-in function dict(). An
empty dictionary can be created by just placing to curly
braces{}.
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary with dict() method Output


Dict = dict({1: ‘God', 2: ‘is', 3:’Good'})
print("\nDictionary with the use of dict(): ") Empty Dictionary:
print(Dict) {}

Dictionary with the use of dict():


# Creating a Dictionary with each item as a Pair {1: ‘God', 2: ‘is', 3: ‘Good'}
Dict = dict([(1, ‘Welcome'), (2, ‘FX')])
print("\nDictionary with each item as a pair: ") Dictionary with each item as a pair:
print(Dict) {1: ‘Welcome', 2: ‘FX'}
Nested Dictionary:

# Creating a Nested Dictionary as shown in the below image


Dict = {1: ‘Welcome', 2: ‘To',
3:{'A' : ‘FX', 'B' : ‘College'}}

print(Dict)

Output
{1: ‘Welcome', 2: ‘To', 3: {'A': ‘FX', 'B': ‘College'}}
Adding elements to a Dictionary

• In Python Dictionary, the addition of elements can be done in


multiple ways. One value at a time can be added to a Dictionary
by defining value along with the key e.g. Dict[Key] = ‘Value’.
Updating an existing value in a Dictionary can be done by using
the built-in update() method. Nested key values can also be
added to an existing Dictionary.
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ") Output
print(Dict)
Empty Dictionary:
# Adding elements one at a time {}
Dict[0] = ‘Welcome'
Dict[2] = 2
Dictionary after adding 2 elements:
print("\nDictionary after adding 2 elements: ")
print(Dict) {0: ‘Welcome', 2: 2}

# Adding set of values to a single Key


Dictionary after adding 3 elements:
Dict['Value_set’] = 3, 4 {0: ‘Welcome', 2: 2, 'Value_set': (3, 4)}
print("\nDictionary after adding 3 elements: ")
print(Dict)
Updated key value:
{0: ‘Welcome', 2: ‘FX', 3: 1, 'Value_set': (3, 4)}
# Updating existing Key's Value
Dict[1] = ‘FX'
print("\nUpdated key value: ")
Adding a Nested Key:
print(Dict) {0: ‘Welcome', 2: ‘FX', 'Value_set': (3, 4), 5: {'Nested': {'1': ‘Welcome',
'2': ‘College'}}}
# Adding Nested Key value to Dictionary
Dict[3] = {'Nested' :{'1' : ‘Welocome', '2' : ‘College'}}
print("\nAdding a Nested Key: ")
print(Dict)
Accessing elements of a Dictionary

#Creating a Dictionary
Dict = {1: ‘God', 'name’: ‘is', 3: ‘Good'}

# accessing a element using key


print("Accessing a element using key:") Output
print(Dict['name'])

Accessing a element using key:


# accessing a element using key is
print("Accessing a element using key:")
print(Dict[1]) Accessing a element using key:
God
Accessing an element of a nested
dictionary

# Creating a Dictionary
Dict = {'Dict1': {1: ‘Welcome'},
'Dict2': {‘Name': ‘FX'}}
{1:‘Wecome’}
# Accessing element using key Welcome
print(Dict['Dict1'])
print(Dict['Dict1'][1]) FX
print(Dict['Dict2']['Name'])
Dictionary methods

clear() – Remove all the elements from the dictionary


copy() – Returns a copy of the dictionary
get() – Returns the value of specified key
items() – Returns a list containing a tuple for each key value pair
keys() – Returns a list containing dictionary’s keys
pop() – Remove the element with specified key
popitem() – Removes the last inserted key-value pair
update() – Updates dictionary with specified key-value pairs
values() – Returns a list of all the values of dictionary
dict1={1:"Python",2:"Java",3:"Ruby",4:"Scala"}
#copy() method

dict2=dict1.copy()
print(dict2)

#clear() method
dict1.clear()
print(dict1)

#get() method
print(dict2.get(1))

#items() method
print(dict2.items())

#keys() method
print(dict2.keys())
#pop() method
dict2.pop(4)
print(dict2)

#popitem() method
dict2.popitem()
print(dict2)

#update() method
dict2.update({3:"Scala"})
print(dict2)

# values() method
print(dict2.values())
{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}
{}
Python
dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')])
dict_keys([1, 2, 3, 4])
{1: 'Python', 2: 'Java', 3: 'Ruby'}
{1: 'Python', 2: 'Java'}
{1: 'Python', 2: 'Java', 3: 'Scala'}
dict_values(['Python', 'Java', 'Scala'])
Finding Key and Value in a Dictionary
• Python dictionary contains key value pairs. we aim to get the
value of the key when we know the value of the element.
Ideally the values extracted from the key but here we are doing
the reverse.
With index and values

• We use the index and values functions of dictionary collection


to achieve this. We design a list to first get the values and then
the keys from it.
dictA = {"Mon": 3, "Tue": 11, "Wed": 8} Output :
# list of keys and values
keys = list(dictA.keys()) Tue
vals = list(dictA.values()) Wed
print(keys[vals.index(11)]) Mon
print(keys[vals.index(8)])
# in one-line
print(list(dictA.keys())[list(dictA.values()).index(3)])
With items

• We design a function to take the value as input and compare it


with the value present in each item of the dictionary. If the
value matches the key is returned.
dictA = {"Mon": 3, "Tue": 11, "Wed": 8}
def GetKey(val):
for key, value in dictA.items():
if val == value:
return key
Ouutput:
return "key doesn't exist" Tue
print(GetKey(11)) Mon
print(GetKey(3)) key doesn't exist
print(GetKey(10))

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