Unit IV Dictionary.ppt
Unit IV Dictionary.ppt
Dictionaries
UNIT – IV DICTIONARIES AND FILES (8)
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
# Creating a Dictionary with Mixed keys Dictionary with the use of Mixed Keys:
{'Name': ‘God', 1: [1, 2, 3, 4]}
print(Dict)
Output
{1: ‘Welcome', 2: ‘To', 3: {'A': ‘FX', 'B': ‘College'}}
Adding elements to a Dictionary
#Creating a Dictionary
Dict = {1: ‘God', 'name’: ‘is', 3: ‘Good'}
# 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
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