Chap - 10
Chap - 10
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.
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
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( )
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.
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
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( )
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
values = sales.values( )
print('Original items:', values)
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( )
Here, when the new dictionary is cleared, the original dictionary is also cleared.
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 }
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
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.
# Empty Set
testSet = set( )
print(testSet, 'length is', len(testSet))
Dictionaries 10-15
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
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.