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

Chap - 10

Uploaded by

Parth Khurana
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)
37 views

Chap - 10

Uploaded by

Parth Khurana
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/ 16

Dictionaries 10-1

Chapter
10

Dictionaries
Key Topics
10.1. Introduction
10.1. Introduction
10.2. Creating a Dictionary
Python dictionary is an unordered collection of items. While
10.3. Access Elements from a Dictionary other compound data types have only value as an element, a
10.4. Looping and Dictionary dictionary has a key: value pair. A dictionary is a data type similar
10.5. Dictionaries and Files
10.6. Add Elements and Update Values In A to arrays, but works with keys and values instead of indexes.
Dictionary Each value stored in a dictionary can be accessed using a key,
10.7. Delete Elements from a Dictionary
10.8. Other Dictionary Operations
which is any type of object (a string, a number, a list, etc.) instead
10.9. Dictionary Methods of using its index to address it. Dictionaries are optimized to retrieve
values when the key is known.
Here in this chapter we will learn Python dictionary; how
they are created, accessing, adding and removing elements from
them and, various built-in methods.
The Python dictionary type is called dict, a dictionary has a
key: value pair.
Dictionaries are optimized to retrieve values when the key
is known.

10.2. Creating a Dictionary


Method 1 : One way to create a dictionary is to start with
the empty dictionary and add key-value pairs. The empty dictionary
is denoted with a pair of curly braces, {}:
>>> engdic = {}
>>> type(engdic)
<class 'dict'>
>>> engdic['one'] = 'Single'
>>> engdic['two'] = 'Double'
>>> engdic['three'] = 'Tripple'
10-2 Dictionaries

The first assignment creates a dictionary named engdic; the other assignments add new key-
value pairs to the dictionary. We can print the current value of the dictionary in the usual way:
>>> print(engdic)
{'three': 'Tripple, 'one': Single', 'two': 'Double'}
The key-value pairs of the dictionary are separated by commas. Each pair contains a key and
a value separated by a colon.
The order of the pairs may not be what you expected. Python uses complex algorithms to
determine where the key-value pairs are stored in a dictionary. For our purposes we can think of this
ordering as unpredictable, so you should not try to rely on it. Instead, look up values by using a
known key.
Method 2 : Another way to create a dictionary is to provide a list of key-value pairs using the
same syntax as the previous output:
>>> engdic = {'one': 'Single', 'two': 'Double', 'three': 'Tripple'}
It doesn't matter what order we write the pairs. The values in a dictionary are accessed with
keys, not with indices, so ordering is unimportant.
Here is how we use a key to look up the corresponding value:
>>> engidc['two']
'Double'
The key 'two' yields the value 'Double'.
Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.
We use a colon to separate each key from its value.
An item has a key and the corresponding value expressed as a pair, key: value.
While values can be of any data type and can repeat, keys must be of immutable type (string,
number or tuple with immutable elements) and must be unique.
Example: # empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'Mango'}
# dictionary with mixed keys
my_dict = {'name': 'Rajesh', 1: [2, 4, 3]}
# using dict( )
my_dict = dict({1:'apple', 2:' Mango '})
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,' Mango ')])
As you can see above, we can also create a dictionary using the built-in function dict( ).
Method 3 : Another way to create a dictionary is through Key Board using input( ).split( )
method.
Dictionaries 10-3

n = int(input("Enter Number of Elements in Dictionary :"))


name = dict(input( ).split( ) for i in range(n))
print(name)
Output
Enter Number of Elements in Dictionary3
1 Rajesh
2 Sumesh
3 Sandeep
{'4': 'Sumesh', '4': 'Sandeep', '6': 'Rajesh'}
Or
n = n=int(input("Enter Number of Elements in Dictionary :"))
name ={}
for i in range(n):
text = input( ).split( )
name[text[0]] = text[1]
print(name)
Output
Enter Number of Elements in Dictionary3
a0001 arvind
a0002 surinder
a0003 sumesh
{'a0001': 'arvind', 'a0003': 'sumesh', 'a0002': 'surinder'}

10.3. Access Elements from a Dictionary


Dictionary uses keys to access values. Key can be used either inside square brackets or with
the get( ) method.
my_dict = {'name':'Rajesh Anand', 'age': 36, 'city':'Amritsar'}
print(my_dict['name'])
print(my_dict.get('city'))
print(my_dict.get('state'))
Output
Rajesh Anand
Amritsar
None
The difference while using get( ) is that it returns None instead of KeyError, if the key is not
found.

10.4. Looping and Dictionary


We can use dictionary as the sequence in for statement. If we loop through a dictionary we will
loop through its keys.
10-4 Dictionaries

#Getting keys through loop


n = n=int(input("Enter Number of Elements in Dictionary :"))
name = dict(input( ).split( ) for i in range(n))
for item in name:
print (item)
Output
Enter Number of Elements in Dictionary: 3
Name Rajesh
Age 34
City Amritsar
Name
Age
City
#Getting Values through loop
n = n=int(input("Enter Number of Elements in Dictionary :"))
name = dict(input( ).split( ) for i in range(n))
for item in name:
(name[item])
Output
Enter Number of Elements in Dictionary: 3
Name Rajesh
Age 34
City Amritsar
35
Amritsar
Rajesh

#Getting the dictionary as a list of value pairs -- a tuple.


n = n=int(input("Enter Number of Elements in Dictionary"))
name = dict(input( ).split( ) for i in range(n))
print(name)
for key, value in name.items( ):
print (key, value)
Output
Enter Number of Elements in Dictionary3
Name Rajesh
City Amritsar
Age 34
{'City': 'Amritsar', 'Age': '34', 'Name': 'Rajesh'}
City Amritsar
Age 34
Name Rajesh
Dictionaries 10-5

10.5. Dictionaries and Files


Files : The open( ) function opens and returns a file handle that can be used to read or write
a file in the usual way.
The code file =open('file_name','w') opens the file into the variable file, ready for writing
operation, and use f.close( ) with finished.
The code file = open('abc.txt', 'r') opens the file into the variable file, ready for reading operations,
and use f.close( ) when finished.
The code file =open('file_name','a') opens the file into the variable file, ready for append operation,
and use f.close( ) with finished.
The standard for-loop works for text files, iterating through the lines of the file. The for-loop
technique is a simple and efficient way to look at all the lines in a text file:
# program to write dictionary into file
file = open('abc.txt', 'a')
n = int(input("Enter Number of Elements in Dictionary :"))
while n>0:
name = input( )
loc = input( )
pair = {'name': name,'loc': loc}
with open('abc.txt', 'a') as file:
file.writelines('{}:{}'.format(k,v) for k, v in pair.items( ))
file.write('\n')
n=n-1

abc.txt-C:/Python33/abc.txt
File Edit Format Run Options Window Help
{'name':'Rajesh','age':20,'city':'Amritsar','4': 'Sumesh', '4': 'Sandeep', '6': 'Rajesh'}

Once the file is written you can read the file with following code.
# program to read dictionary from a file
file = open('abc.txt', 'r')
for line in file:
print(line) ## since 'line' already includes the end-of line.
file.close( )

10.6. Add Elements and Update Values In A Dictionary


Dictionaries are mutable. We can add new items or change the value of existing items using
assignment operator. If the key is already present, value gets updated, else a new key: value pair is
added to the dictionary.
10-6 Dictionaries

my_dict = {'name':'Rajesh Anand', 'age': 36, 'city':'Amritsar'}


# add item
my_dict['state'] = 'Punjab'
print(my_dict)
# update value
my_dict['age'] = 37
print(my_dict)
Output
{'AGE': 36, 'CITY': 'AMRITSAR', 'NAME': 'RAJESH ANAND', 'STATE': 'PUNJAB'}
{'AGE': 37, 'CITY': 'AMRITSAR', 'NAME': 'RAJESH ANAND', 'STATE': 'PUNJAB'}

10.7. Delete Elements from a Dictionary


del( ) : The del statement removes a key-value pair from a dictionary. For example, the
following dictionary contains the names of various fruits and the number of each fruit in stock:
>>> inventory = {'apples': 30, 'bananas': 32, 'oranges': 25, mangoes': 17}
>>> print(inventory)
{'apples': 30, 'bananas': 32, 'mangoes': 17, 'oranges': 25}
If someone buys all of the mangoes, we can remove the entry from the dictionary:
>>> del inventory['mangoes']
>>> print(inventory)
{'apples': 30, 'bananas': 32, 'oranges': 25}
Or if we're expecting more mangoes soon, we might just change the value associated with
mangoes:
>>> inventory['mangoes'] = 0
>>> print(inventory)
{'apples': 30, 'bananas': 32, 'mangoes': 0, 'oranges': 25}

10.8. Other Dictionary Operations


len( ) : The len function also works on dictionaries; it returns the number of key-value pairs:
>>> len(inventory)
4
In Operator : The in operator returns True if the key appears in the dictionary and False
otherwise:
>>> 'mangoes' in inventory
True
>>> 'blueberries' in inventory
False
sorted( ) : Python's built-in sorted function returns a list of dictionaries keys in sorted order:
>>> sorted(inventory)
['apples', 'bananas', 'mangoes','oranges']
Dictionaries 10-7
Aliasing and copying : Because dictionaries are mutable, you need to be aware of aliasing.
Whenever two variables refer to the same object, changes to one affect the other.
If you want to modify a dictionary and keep a copy of the original, use the copy method. For
example, opposites are a dictionary that contains pairs of opposites:
>>> opposites = {'up': 'down', 'right': 'wrong', 'true': 'false'}
>>> an_alias = opposites
>>> a_copy = opposites.copy( )
an_alias and opposites refer to the same object; a_copy refers to a fresh copy of the same
dictionary. If we modify alias, opposites is also changed:
>>> an_alias['right'] = 'left'
>>> opposites['right']
'left'
If we modify a_copy, opposites is unchanged:
>>> a_copy['right'] = 'privilege'
>>> opposites['right']
'left'

10.9. Dictionary Methods


Python has some methods that dictionary objects can call. For example, dict1.clear( ) method
removes all items from the dictionary dict1.
This page includes all dictionary methods available in Python 3. Also, the page includes built-in
functions that can take dictionary as a parameter and perform some task. For example, the sort( )
function can take dictionary as a parameter and sort it.
In-Build Method of Dictionary
Method Description
clear( ) Removes all Items
copy( ) Returns Shallow Copy of a Dictionary
fromkeys( ) creates dictionary from given sequence
get( ) Returns Value of The Key
items( ) returns view of dictionary's (key, value) pair
keys( ) Returns View Object of All Keys
popitem( ) Returns & Removes Element From Dictionary
setdefault( ) Inserts Key With a Value if Key is not Present
pop( ) removes and returns element having given key
values( ) returns view of all values in dictionary
update( ) Updates the Dictionary
10-8 Dictionaries
Other in-build functions that can be applied on Dictionaries
any( ) Checks if any Element of an Iterable is True
all( ) returns true when all elements in iterable is true
ascii( ) Returns String Containing Printable Representation
bool( ) Coverts a Value to Boolean
dict( ) Creates a Dictionary
enumerate( ) Returns an Enumerate Object
filter( ) constructs iterator from elements which are true
iter( ) returns iterator for an object
len( ) Returns Length of an Object
max( ) returns largest element
min( ) returns smallest element
map( ) Applies Function and Returns a List
sorted( ) returns sorted list from a given iterable
sum( ) Add items of an Iterable
zip( ) Returns an Iterator of Tuples

How to change or add elements in a dictionary?


pop( ) Me thod : The pop( ) method removes and returns an element from a dictionary having
the given key.

The syntax of pop( ) method is


dictionary.pop(key[, default])

# Pop an element from the dictionary


# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
element = sales.pop('apple')
print('The popped element is:', element)
print('The dictionary is:', sales)
Output
The popped element is: 2
The dictionary is: {'orange': 3, 'grapes': 4}
Dictionaries 10-9

#Pop an element not present from the dictionary


# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }

element = sales.pop('guava')
print('The dictionary is:', element)
Output
KeyError: 'guava'
popitem( ) Method : The popitem( ) returns and removes an arbitrary element (key, value)
pair from the dictionary. The method, popitem( ) can be used to remove and return an arbitrary item
(key, value) form the dictionary. All the items can be removed at once using the clear( ) method.
The syntax of popitem( ) is:
dict.popitem( )
Note : Arbitrary elements and random elements are not same. The popitem( ) doesn't return a
random element.

person = {'name': 'Phill', 'age': 22, 'salary': 3500.0}


result = person.popitem( )
print('person = ',person)
print('Return Value = ',result)
Output
person = {'name': 'Phill', 'salary': 3500.0}
result = ('age', 22)

The popitem( ) raises a KeyError error if the dictionary is empty.


clear( ) Method : The clear( ) method removes all items from the dictionary.

The syntax of clear( ) is:


dict.clear( )

# How clear( ) method works for dictionaries?


d = {1: "one", 2: "two"}
d.clear( )
print('d =', d)
Output
d = {}

You can also remove all elements from the dictionary by assigning empty dictionary {}.
However, there is a difference between calling clear( ) and assigning {} if there is another
variable referencing the dictionary.
10-10 Dictionaries

# How assigning { } works in dictionaries to delete dictionaries?


d = {1: "one", 2: "two"}
d1 = d
d.clear( )
print('Removing items using clear( )')
print('d =', d)
print('d1 =', d1)

d = {1: "one", 2: "two"}


d1 = d
d = {}
print('Removing items by assigning {}')
print('d =', d)
print('d1 =', d1)
Output
Removing items using clear( )
d = {}
d1 = {}
Removing items by assigning {}
d = {}
d1 = {1: 'one', 2: 'two'}

items( ) Method : The items( ) method returns a view object that displays a list of dictionary's
(key, value) tuple pairs.
The syntax of items( ) method is:
dictionary.items( )

#Get all items of a dictionary with items( )


# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }

print(sales.items( ))
Output
dict_items([('apple', 2), ('orange', 3), ('grapes', 4)])

values( ) Method : The values( ) method returns a view object that displays a list of all the
values in the dictionary.
The syntax of values( ) is:
dictionary.values( )
Dictionaries 10-11

#Get all values from the dictionary


# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print(sales.values( ))
Output
dict_values([2, 4, 3])

#How values( ) works when dictionary is modified?


# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }

values = sales.values( )
print('Original items:', values)

# delete an item from dictionary


del[sales['apple']]
print('Updated items:', values)
Output
Original items: dict_values([2, 4, 3])
Updated items: dict_values([4, 3])

The view object values doesn't itself return a list of sales item values but it returns a view of all
values of the dictionary.
If the list is updated at any time, the changes are reflected on to the view object itself, as shown
in the above program.
copy( ) Method : They copy( ) method returns a shallow copy of the dictionary.
The syntax of copy( ) is:
dict.copy( )

#How copy works for dictionaries?


original = {1:'one', 2:'two'}
new = original.copy( )

print('Orignal: ', original)


print('New: ', new)
Output
Orignal: {1: 'one', 2: 'two'}
New: {1: 'one', 2: 'two'}
10-12 Dictionaries
Difference in Using copy( ) method, and = Operator to Copy Dictionaries
When copy( ) method is used, a new dictionary is created which is filled with a copy of the
references from the original dictionary.
When = operator is used, a new reference to the original dictionary is created.
#Using = Operator to Copy Dictionaries
original = {1:'one', 2:'two'}
new = original

# removing all elements from the list


new.clear( )

print('new: ', new)


print('original: ', original)
Output
new: {}
original: {}

Here, when the new dictionary is cleared, the original dictionary is also cleared.

#Using copy( ) to Copy Dictionaries


original = {1:'one', 2:'two'}
new = original.copy( )

# removing all elements from the list


new.clear( )

print('new: ', new)


print('original: ', original)
Output
new: {}
original: {1: 'one', 2: 'two'}

Here, when the new dictionary is cleared, the original dictionary remains unchanged.
#Display Key, Values and items in dictionary
marbles = {"red": 34, "green": 30, "brown": 31, "yellow": 29 }

# Get a value by its key, or None if it doesn't exist


marbles.get("orange")
Dictionaries 10-13

# We can specify a different default


marbles.get("orange", 0)

# Add several items to the dictionary at once


marbles.update({"orange": 34, "blue": 23, "purple": 36})

# All the keys in the dictionary


print(marbles.keys( ))
# All the values in the dictionary
print(marbles.values( ))
# All the items in the dictionary
print(marbles.items( ))
Output
dict_keys(['blue', 'orange', 'green', 'brown', 'purple', 'yellow', 'red'])
dict_values([23, 34, 30, 31, 36, 29, 34])
dict_items([('blue', 23), ('orange', 34), ('green', 30), ('brown', 31), ('purple', 36),
('yellow', 29), ('red', 34)])

fromkeys( ) Method : The fromkeys( ) method creates a new dictionary from the given
sequence of elements with a value provided by the user.
The syntax of fromkeys( ) method is:
dictionary.fromkeys(sequence[, value])
fromkeys( ) Parameters
The fromkeys( ) method takes two parameters:
• sequence - sequence of elements which is to be used as keys for the new dictionary
• value (Optional) - value which is set to each each element of the dictionary
Return value from fromkeys( )
The fromkeys( ) method returns a new dictionary with the given sequence of elements as the
keys of the dictionary.
If the value argument is set, each element of the newly created dictionary is set to the provided
value.
#Create a dictionary from a sequence of keys
# vowels keys
keys = {'a', 'e', 'i', 'o', 'u' }

vowels = dict.fromkeys(keys)
print(vowels)
Output
{'a': None, 'u': None, 'o': None, 'e': None, 'i': None}
10-14 Dictionaries

#Create a dictionary from a sequence of keys with value


# vowels keys
keys = {'a', 'e', 'i', 'o', 'u' }
value = 'vowel'

vowels = dict.fromkeys(keys, value)


print(vowels)
Output
{'a': 'vowel', 'u': 'vowel', 'o': 'vowel', 'e': 'vowel', 'i': 'vowel'}

#Create a dictionary from mutable object list


# vowels keys
keys = {'a', 'e', 'i', 'o', 'u' }
value = [1]

vowels = dict.fromkeys(keys, value)


print(vowels)

# updating the value


value.append(2)
print(vowels)
Output
{'a': [1], 'u': [1], 'o': [1], 'e': [1], 'i': [1]}
{'a': [1, 2], 'u': [1, 2], 'o': [1, 2], 'e': [1, 2], 'i': [1, 2]}

If the provided value is a mutable object (whose value can be modified) like list, dictionary, etc.,
when the mutable object is modified, each element of the sequence also gets updated.
This is because, each element is assigned a reference to the same object (points to the same
object in the memory).
To avoid this issue, we use dictionary comprehension.

# How len( ) works with dictionaries and sets?


testSet = {1, 2, 3}
print(testSet, 'length is', len(testSet))

# Empty Set
testSet = set( )
print(testSet, 'length is', len(testSet))
Dictionaries 10-15

testDict = {1: 'one', 2: 'two'}


print(testDict, 'length is', len(testDict))

testDict = {}
print(testDict, 'length is', len(testDict))

testSet = {1, 2}
# frozenSet
frozenTestSet = frozenset(testSet)
print(frozenTestSet, 'length is', len(frozenTestSet))
Output
{1, 2, 3} length is 3
set( ) length is 0
{1: 'one', 2: 'two'} length is 2
{} length is 0
frozenset({1, 2}) length is 2

Frequently Asked Questions


Q.1. What is dictionary? Explain different methods of creating dictionary.
Q.2. Explain different operations that can be performed on dictionary.
Q.3. Discuss few functions of dictionary?
Q.4. Discuss various methods of dictionary?

Exercise
Q.1. Create a dict directory which stores telephone numbers (as string values), and populate it
with these key-value pairs:
Name Telephone number
Rajesh Anand 9872862518
Ranjit Sing 9872455515
Sanjeev Kumar 8244562466
1. Change Rajesh's number to 7852462662
2. Add a new entry for a person called Aman Chopra with the phone number 9872452342
3. Print Sanjeev's number.
4. Print all the keys.
5. Print all the values.
6. Print all the keys and values.

You might also like