Python Dictonary
Python Dictonary
2
Python Dictionary :
Like Python lists there is not indexing exists in Python dictionary. The values can
only be accessed by its key.
Let us take the example of computer network ports.
>>> port1 = { 22: “SSH”, 23 : ‘Telnet’, 80: “HTTP”, 53: “DNS”, 443: “HTTPS” }
>>> port1[22]
‘SSH’
>>> port1[53]
‘DNS’
>>> port1[67]
The has key() method return the True and False statement.
>>> port1.has_key(22)
True
>>> port1.has_key(24)
False
>>>
By using in operator
>>> if 22 in port1:
… print “Key found”
…
Key found
>>>
12
Copyright @ 2018 Learntek. All Rights Reserved.
Delete Elements of Python dictionary
In order to iterate over the Python dictionary, we used items() or iteritems() method.
The items() method return a list of tuple pairs. The iteritems() method is the iterator
which saves the memory.
In Python 3 the iteritems() method has been removed and items() method works as
iteritems().
port1 = {22: “SSH”,23:’Telnet’,80: “HTTP”, 53: “DNS”, 443: “HTTPS” }
for k, v in port1.items():
print k, ” : ” ,v
{ 80: ‘HTTP’, 443: ‘HTTPS’, 53: ‘DNS’, 22: ‘SSH’, 23: ‘Telnet’ }
So far you learned Python dictionary creation, deleting an item, adding an item,
updating items. Let us create a copy of an existing dictionary. In order to make a copy
of a dictionary, we will use the copy() method.
>>> port1 = {80: ‘HTTP’, 443: ‘HTTPS’, 53: ‘DNS’ }
>>> port2 = port1.copy()
>>> port2
{80: ‘HTTP’, 443: ‘HTTPS’, 53: ‘DNS’}
>>> id(port1)
47341080L
>>> id(port2)
47374680L
>>>
Copyright @ 2018 Learntek. All Rights Reserved. 18
In the above example, a new dictionary, port2, which is the copy of port1 has
been created.
The memory addresses of both the dictionary are different.
Practical example
Let us create a dictionary by using 2 lists
list1 = [1 ,2, 3, 4]
list2 = [ ‘a’, ‘b’, ‘c’, ‘d’ ]
dict1 = { }
for i in xrange( len(list1) ):
dict1[list1[i]] = list2[i]
print dict1
Output:
Email : [email protected]