Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Chapter-13 Dictionaries

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 single value as an element,
Dictionary holds key:value pair. Key value is provided in the dictionary to make it more
optimized. XIF={1:”Alok”, 3:”Deepak”, 4:”Deepak”}
Note – Keys in a dictionary doesn’t allows Polymorphism (within a dictionary key cannot
be repeated).

Creating a Dictionary

In Python, a Dictionary can be created by placing sequence of elements within


curly {} braces, separated by ‘comma’. Dictionary holds a pair of values, one being the Key
and the other corresponding pair element being its value, Key:value.
Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be
repeated and must be immutable.

Note – Dictionary keys are case sensitive, same name but different cases of Key will be
treated distinctly.
Syntax for creating a dictionary:
<dictionary_name>={<key>:<value>, <key>:<value>………}

Hobbies={“Alok”:”music”,“Deepak”:“cricket”, “Sejal” : “Dancing”,


“Kamal” : “music” }
Curly brackets { } mark the beginning and end of the dictionary.
Each element consists of a key : value pair (shown with different colors ), the key and value
of each element are separated by a colon( : ) .

# empty dictionary
my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a pair


my_dict = dict([(1,'apple'), (2,'ball')])

Accessing Elements from Dictionary

While indexing is used with other data types to access values, a dictionary uses keys . Keys
can be used either inside square brackets [] or with the get() method.
If we use the square brackets [] , KeyError is raised in case a key is not found in the
dictionary. On the other hand, the get() method returns None if the key is not found.

# get vs [] for retrieving elements


my_dict = {'name': 'Alok', 'age': 26}

# Output: Alok
print(my_dict['name'])

# Output: 26
print(my_dict.get('age'))

# Trying to access keys which doesn't exist throws error


# Output None
print(my_dict.get('address'))

# KeyError
print(my_dict['address'])

Output

Alok
26
None
Traceback (most recent call last):
File "<string>", line 15, in <module>
print(my_dict['address'])
KeyError: 'address
Giving just the name of dictionary in print( ) displays the entire contents of the dictionary,
as with all data types, but look at the following example and mark an interesting fact about
dictionaries.

# printing all the elements


d = {'name': 'Alok', 'age': 26, 'address': ‘Rdp’}
print(d)
print(d)

Output

{'name': 'Alok', 'age': 26, 'address': ‘Rdp’}


{'age': 26, 'name': 'Alok','address': ‘Rdp’}

So we see unlike other sequences, the elements (key:value) of a dictionary do not have fix
order, they may appear in any order, so we say dictionaries are unordered. We cannot
access element as per specific order (no indexing of elements). The only way to access a
value is through its key. Thus we can say that keys act like indexes to access value from a
dictionary.
Iterating Through a Dictionary
We can iterate through each key in a dictionary using a for loop.

# Iterating through a Dictionary


L=[12,4,5,7]
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])

Output

1
9
25
49
81

In above program loop variable i will be assigned the keys of the dictionary squares, one at
a time, now we can access values for that particular key using squares[ i ]. As dictionaries
are unordered, the order of assignment of keys to variable i may be differ in every run.

So, we can access both keys and values form the same loop.
# Iterating through a Dictionary
d2={"alok":9908876910,"Kamal":7766554433,"Lalit":7192837465}
for i in d2:
print(i,”- ->”,d2[i]) # i will give key and d2[i] its corresponding value

Output
alok --> 9908876910

Kamal --> 7766554433

Lalit --> 7192837465

Accessing all Keys or all Values in one go is also possible. We can use <dictionary>.keys( ),
to see all the keys in dictionary, likewise <dictionary>.values( ) will return all the values in
one go.
# Accessing Keys and values in one go
d1={10:"alok",11:"Kamal",12:"Lalit",13:"Deepak"}
print(d1.keys())

print(d1.values())

Output
dict_keys([10, 11, 12, 13])

dict_values(['alok', 'Kamal', 'Lalit', 'Deepak'])

The keys() and values() function return all the keys or values in form of a sequence, we can
convert them, to other sequences. Example
# Converting Keys and values to List/Tuple
d1={10:"alok",11:"Kamal",12:"Lalit",13:"Deepak"}
L=list(d1.keys()) # Will convert collection of all keys to list
print (L)
T=tuple(d1.values())#Will convert collection of all values to tuple
print (T)

Output
[10, 11, 12, 13]

('alok', 'Kamal', 'Lalit', 'Deepak')


Characteristics of a Dictionary

1. Unordered set: Key value pair or an element may appear in any order so they are
unordered set of elements.
2. Not a sequence: Unlike list, string or tuples dictionary is not a sequence as no
indexes are used.
3. Indexed by Keys, not numbers.
4. Keys in a Dictionary must be unique and immutable. The keys of a dictionary
identify a value, so keys must be of immutable type (not to be changed), we can use
string or number as key, even a tuple if contains all immutable elements , can be
used as a key. The values on other can be of any type.
#Mixed data type keys and values
dict1={1:"integer as key", "two":2,(3,"hello"):"tuple as key",
4:[12,"a"]}
print(dict1[1])#integer as key, string as value
print(dict1[“two”])#string as key, int as value
print(dict1[(3,"hello")])#Tuple as key, string value
print(dict1[4])# Int as key, List as value

Output
integer as key
2
tuple as key
[12, 'a']
5. Dictionaries are Mutable:- Like lists dictionaries are also mutable, we can change
value of a certain key in place using assignment operator:-
<dictionary>[key]=<new value>
For example in above dictionary dict1 we can change the value of key 1 by:-
#changing value of a key
dict1[1]=111
print(dict1[1])
the above statement will change the value of key 1 in the dictionary to 111 (not
only value changed but data type too.
An interesting fact, if the key does not exist in the dictionary, a new key:value pair
is added to the dictionary
#Adding new key:value pair
dict1[5]=”five” # Will add a new element
print(dict1)
Output
{1: 111, 'two': 2, (3, 'hello'): 'tuple as key', 4: [12, 'a'],
5: 'five'}

dict1[5]=”five” adds a new element (5:”five”),to the dictionary as


no key as 5 is found in dictionary.

Creating Dictionary:- There are many ways for creating Python Dictionary:-

1. Initializing a dictionary:- write key:value pairs separated by commas within curly


brackets.
d1={10:"alok",11:"Kamal",12:"Lalit",13:"Deepak"}
2. Creating Empty Dictionary:- An empty dictionary can be created in two ways-
i) dd={ }
ii) dd= dict( )

Now we can add elements to this dictionary:-

dd[“name”]=”Alok”

dd[“roll”]= 12

This method is used to create dictionary dynamically, at run time.


dd={}
for x in range(5):
roll=int(input(“Enter Roll “))
name=input(“Name “)
dd[roll]=name
dd={2:”Alok”,12:”Deepak,4:”Amit”}
Create a dictionary from key and value pairs:- Using dict() constructor, we can create a
new dictionary initialized from specified set of key and value pairs. There a number of
ways to provide keys and values to dict() constructor.

i) Specific key value pair as keyword arguments to dict(), Keys as arguments and
values as their value. The argument names (keys) are string type
# Keys and values as keyword arguments
s2=dict(name='alok',Class=11,roll=12)
print(s2)

output
{'name': 'alok', 'Class': 11, 'roll': 12}

ii) Specify comma-separated key:value pairs:- enclose comma separated


key:value pairs within curly brackets.

# Passing comma-separated key:value pairs


s2=dict({'name':'alok','class':11,'roll':12})
print(s2)

output
{'name': 'alok', 'Class': 11, 'roll': 12}

iii) Specify keys and corresponding values separately:- In this method keys and
corresponding values are enclosed in parenthesis and are passed as an
argument to the zip() function, which is then given as argument to dict().

# Specify keys and corresponding values separately


s2=dict(zip(('name','class','roll'),('alok',11,12)))
print(s2)

output
{'name': 'alok', 'Class': 11, 'roll': 12}

iv) Creating dictionary from sequences:- We can pass sequences (list or tuple) as
argument to dict(). The list/tuple passed is nested, having key and value as single
element.

# Creating dictionary from sequences


#Passing key value pairs as nested list
s2=dict([['name','alok'],['class',11],['roll',12]])
print(s2)
#Passing key value pairs as nested tuple
s2=dict((('name','alok'),('class',11),('roll',12)))
print(s2)

output
{'name': 'alok', 'Class': 11, 'roll': 12}
{'name': 'alok', 'Class': 11, 'roll': 12}

You might also like