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

Dictionary

Uploaded by

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

Dictionary

Uploaded by

supriya sundaram
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Dictionary

 Dictionary
 Dictionaries are used to store data values in key:value pairs.
 A dictionary is a collection which is ordered*, changeable and
do not allow duplicates.
 As of Python version 3.7, dictionaries are ordered.
 In Python 3.6 and earlier, dictionaries are unordered.
 Dictionaries are written with curly brackets, and have keys
and values:
 A pair of braces creates an empty dictionary: {}.
 Placing a comma-separated list of key:value pairs within the
braces adds initial key:value pairs to the dictionary
 Example
 D={}
 #Empty Dictionary
 print(type(D))
 # Dictionary Creation
 D={1:"Arun",2:"Aravind",3:"Boomesh",4:"Divya"}
print(D)
Dictionary
 Dictionary
 The main operations on a dictionary are storing a value with
some key and extracting the value given the key.
 It is also possible to delete a key:value pair with del.
 If you store using a key that is already in use, the old value
associated with that key is forgotten.
 It is an error to extract a value using a non-existent key.
Accessing Dictionary Elements
To access dictionary elements, you can use the familiar
square brackets along with the key to obtain its value.
Following is a simple example.
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print( "dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
Output:
dict['Name']: Zara
dict['Age']: 7
update a dictionary by adding a new entry or a key-
value pair, modifying an existing entry, or deleting an
existing entry as shown below in the simple example
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
print(dict)

OUTPUT
dict['Age']: 8
dict['School']: DPS School
{'Name': 'Zara', 'Age': 8, 'Class': 'First', 'School': 'DPS School'}
Delete Dictionary Elements

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


del dict['Name']; # remove entry with key 'Name'
print(dict)
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
OUTPUT
{'Age': 7, 'Class': 'First'}
List vs Tuple Vs Dictionary
Lists Tuples Dictionaries

A dictionary is
A list is a A tuple is an unordered colle
collection an ordered collecti ction of data that
of ordered data. on of data. stores data in key-
value pairs.

Dictionaries are
Tuples mutable and keys
Lists are mutable.
are immutable. do not allow
duplicates.

Creating an empty Creating an empty


Creating an empty
list Tuple
dictionary
l=[] t=()
d={}

You might also like