DICTIONARIES
WHAT IS DICTIONARY?
WHAT IS
DICTIONARY?
• A dictionary is a collection data type
that is used to store data values in
key:value pairs. It is ordered,
changeable and do not allow
duplicates.
A dictionary is an extremely useful data
storage construct for storing and
retrieving all key value pairs, where
each element is accessed (or indexed)
by a unique key.
A dictionary is a collection of indices
called as keys and a collection of
values. Each key is associated with a
single value.
The association of a key and a value
is called as key-value pair or
sometimes as item.
KEY -VALUE PAIR
We can refer to a
dictionary as a mapping
between a set of indices
(which are called keys) and a
set of values. Each key maps a
value. The association of a key
and a value is called a key-
value pair.
Syntax:
my_dict = {'key1':
DICTIONARIES
Curley brackets are used to repres
ent a dictionary.
Each pair in the dictionary is
represented
by a key and value separated by a
colon.
Multiple pairs are separated by
comas
DICTIONARIES
A dictionary is an un
ordered collection of key-
value pairs.
A dictionary has a length, specific
ally the number of key-value pairs.
A dictionary provides fast look up
by key.
The keys must be immutable obje
ct types.
STATE DIAGRAM
>>>
A={1:"one",2:"two",3:"three
"} 1 one
A= 2 two
3 three
KEY VALUES
S
CREATING A DICTIONARY
– dict()
CREATING DICTIONARAY – dict()
The function dict ( ) is used to
create a new dictionary with no
items. This function is called built-
in function. We can also create
dictionary using {}.
CREATING DICTIONARAY – Example
CREATING AND TRAVERSING
DICTIONARAY
CREATING AND TRAVERSING
DICTIONARAY
OUT PUT
CREATING AND TRAVERSING
DICTIONARAY
OUT PUT
ACCESSING VALUES IN
DICTIONARY:
• To access dictionary elements, you use the
familiar square brackets along with the key to
obtain its value:
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class':
'First'};
Print("dict['Name']: ", dict['Name’](;
print (“dict['Age']: ", dict['Age’]);
• This will produce following result:
dict['Name']: Zara
dict['Age']: 7
• If we attempt to access a data item with a key
which is not part of the dictionary, we get an error
as follows:
dict = {'Name': 'Zara', 'Age': 7, 'Class':
'First'};
print("dict['Alice']: ", dict['Alice’]);
• This will produce following result:
dict['Zara']:
Traceback (most recent call last): File "test.py",
line 4, in <module> print "dict['Alice']: ",
dict['Alice']; KeyError: 'Alice'
UPDATING DICTIONARY:
• You can update a dictionary by adding a new entry or item (i.e.,
a key-value pair), modifying an existing entry, or deleting an
existing entry as shown below:
• 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'];
• This will produce following result:
dict['Age']: 8
dict['School']: DPS School
DELETE DICTIONARY ELEMENTS:
• You can either remove individual dictionary elements or clear the entire contents
of a dictionary. You can also delete entire dictionary in a single operation.
• To explicitly remove an entire dictionary, just use the del statement:
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # remove entry with key 'Name’
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
• This will produce following result. Note an exception raised, this is because after
del dict dictionary does not exist any more:
dict['Age']:
Traceback (most recent call last): File "test.py", line 8, in <module> print
"dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
• Note: del() method is discussed in subsequent section.
PROPERTIES OF DICTIONARY
KEYS:
• Dictionary values have no restrictions. They can be any arbitrary
Python object, either standard objects or user-defined objects.
However, same is not true for the keys.
• There are two important points to remember about dictionary keys:
• (a) More than one entry per key not allowed. Which means no
duplicate key is allowed. When duplicate keys encountered during
assignment, the last assignment wins.
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};
print "dict['Name']: ", dict['Name'];
• This will produce following result:
dict['Name']: Manni
• (b) Keys must be immutable. Which means you can use
strings, numbers, or tuples as dictionary keys but
something like ['key'] is not allowed.
• Example:
dict = {['Name']: 'Zara', 'Age': 7};
print "dict['Name']: ", dict['Name'];
• This will produce following result. Note an exception
raised:
Traceback (most recent call last):
File "test.py", line 3, in <module> dict = {['Name']:
'Zara', 'Age': 7};
TypeError: list objects are unhashable
BUILT-IN DICTIONARY FUNCTIONS
& METHODS:
SN Function with Description
1 cmp(dict1, dict2)
Compares elements of both dict.
2 len(dict)
Gives the total length of the dictionary. This would be equal to the number
of items in the dictionary.
3 str(dict)
Produces a printable string representation of a dictionary
4 type(variable)
Returns the type of the passed variable. If passed variable is dictionary
then it would return a dictionary type.
DICTIONARAY – BUILT IN
METHODS
DICTIONARAY – BUILT IN
METHODS
Dictionary Meaning
Method
dict.clear() Removes all the
elements of the
dictionary
dict.copy() Returns (shallow)copy
of dictionary.
dict.get(key, for key key, returns
default=None) value or default if key
not in dictionary (note
that default's default is
None)
DICTIONARAY – BUILT IN
METHODS
Dictionary Meaning
Method
dict.keys() returns list of dictionary
dict's keys
dict.setdefault similar to get(), but will
key, set dict[key]=default if
default=None key is not already in dict
dict.update(dict adds dictionary dict2's
2) key-values pairs to dict
dict.values() returns list of dictionary
dict's values
DICTIONARAY – BUILT IN
METHODS
Dictionary Meaning
Method
dict.pop() returns list of dictionary
dict's keys
dict.popitem() similar to get(), but will
set dict[key]=default if
key is not already in dict
dict.clear() METHOD
clear
method
OUTPUT is in next
dict.clear() METHOD -
OUTPUT
Birthday dictionary
dict.copy() METHOD
copy
method
OUTPUT is in next
dict.copy() METHOD -
OUTPUT
copy method creates b2
dictionary
dict.get() METHOD
get
method
OUTPUT is in next
dict.get() METHOD -
OUTPUT
Creating a b2 dictionary using
get method
dict.items() METHOD
items
method
OUTPUT is in next
dict.items() METHOD -
OUTPUT
items method returns dictionary
content
dict.keys() METHOD
keys
method
OUTPUT is in next
dict.keys() METHOD -
OUTPUT
keys method returns
dictionary keys
dict.update() METHOD
update
method
dict.values() METHOD
values method returns
dictionary values
dict.pop() METHOD
pop method removes
specified key values from the
dict.popitem() METHOD
popitem method removes
values/items from the
CLASS WORK/HOME WORK
CLASS WORK/HOME
1. Write a Python WORK
script to sort
(ascending and descending) a
dictionary by value.
2. Write a Python script to add a key
to a dictionary.
Sample Dictionary : {0: 10, 1: 20}
Expected Result : {0: 10, 1: 20, 2: 30}
3. Write a Python script to
concatenate following dictionaries to
create a new one.
Sample Dictionary :
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
Expected Result : {1: 10, 2: 20, 3: 30,
CLASS WORK/HOME WORK
4. Write a Python script to check if a
given key already exists in a
dictionary.
5. Write a Python program to iterate
over dictionaries using for loops.
6. Write a Python script to generate
and print a dictionary that contains a
number (between 1 and n) in the
form (x, x*x).
Sample Dictionary ( n = 5) :
Expected Output : {1: 1, 2: 4, 3: 9, 4:
16, 5: 25}
CLASS WORK/HOME WORK
7. Write a Python script to print a
dictionary where the keys are
numbers between 1 and 15 (both
included) and the values are square
of keys.
Sample Dictionary
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7:
49, 8: 64, 9: 81, 10: 100, 11: 121, 12:
144, 13: 169, 14: 196, 15: 225}
8. Write a Python script to merge two
Python dictionaries.
CLASS WORK/HOME WORK
9. Write a Python program to iterate
over dictionaries using for loops.
10. Write a Python program to sum
all the items in a dictionary.
Class Test
Class Test
Time: 40 Min Max
Marks: 20
1. What is dictionary? give
example 02
2. Write a python script to
traverse a dictionary
05
3. Explain 5 list built in
methods of dictionary
THANK YOU