Python Dictionary

Python Dictionary

Python Dictionary :

A Python dictionary is a sequence of key/value or item pairs separated by commas.

A Python dictionary is created by using curly braces ( { } ).

Syntax to create empty dictionary.

< variable-name > = {}

Or

< variable-name > = dict()

Syntax to create Python dictionary with items

<variable-name> = { key : value , key : value }

The pair of key and value is called item, key and value are separated by colon ( : ). The Each item is separated by comma ( , ), whole thing is enclosed in curly braces ( { } ).

Features of Python dictionary

  1. The key of Python dictionary can not be changed.
  2. The value of key can be changed.
  3. Ordering is not significant, the order in which you have entered the items in dictionary, may not get the items in same order.

Features of Python dictionary’s key

Key are unique in the Python dictionary. We can not assign same key again.

Let us see the example.

>>> dict1 = {“Mohit” : 1, “Rahul” : 2, “Mohit” : 3}

>>> dict1

{‘Mohit’: 3, ‘Rahul’: 2}

>>>

Key are unique in the Python dictionary. We can not assign same key again.

In the above example, we used the same key “Mohit” two times although the program is not giving any error. But You can see the most recent key replaced the old one.

The int, float, and string can be used as a key. Tuple which does not contain any list can be used as a key. Let us see the example.

>>> tuple = ()

>>> dict2 = {tuple : “a”}

>>> dict2

{(): ‘a’}

>>> tuple1 = ( [],9 )

>>> dict2 = { tuple1 : “a” }

Traceback (most recent call last):

File “<stdin>”, line 1, in <module>

TypeError: unhashable type: ‘list’

>>>

In the example, it is very clear if a tuple with a list is used then the interpreter will give the error.

Features of Python Dictionary’s value.

The value can be repeated.

You can store any thing in the value.

Adding and updating the value from dictionary

Let us create an empty dictionary and add some items.

>>> AV = {}

>>> AV[ ‘IRON-MAN’ ] = “Tony Stark”

>>> AV[ ‘Thor’ ] = “Chris”

>>> AV

{ ‘IRON-MAN’ : ‘Tony Stark’, ‘Thor’ : ‘Chris’ }

>>>

Let us update the values ‘Chris’.

>>> AV[ ‘Thor’ ] = “Chris Hemsworth”

>>> AV

{‘IRON-MAN’ : ‘Tony Stark’, ‘Thor’ : ‘Chris Hemsworth’}

>>>

You have seen we can update the value by using the dictionary’s key.

python training

Accessing the values of 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]

Traceback (most recent call last):

File “<stdin>”, line 1, in <module>

KeyError: 67

You can see if a key does not exist then the interpreter shows error. In order to tackle this problem then get() method is used. See the example below.

>>> port1.get(53, “not found” )

‘DNS’

>>> port1.get(67, “not found” )

‘not found’

>>>

Instead of error a customize message get printed.

Different type of ways to check the existence of a key

In this section, we’ll see how to check whether a particular key exists or not.

You have already see the get() method.

>>> port1.get( 22, “Key not found”)

‘SSH’

>>> port1.get( 24, “Key not found”)

‘Key not found’

>>>

Has_key()

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

>>>

Delete Elements of Python dictionary

you can delete a single element of the dictionary as well entire dictionary.

Example

>>> port1 = {22: “SSH”, 23 : ‘Telnet’,80: “HTTP”, 53: “DNS”, 443: “HTTPS”}

>>> del port1[22]

>>> port1

{80: ‘HTTP’, 443: ‘HTTPS’, 53: ‘DNS’, 23: ‘Telnet’}

>>> del port1

>>> port1

Traceback (most recent call last):

File “<stdin>”, line 1, in <module>

NameError: name ‘port1’ is not defined

You can see the error because dictionary named port does exist after command del port1.

Iterating the Python dictionary using for loop

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

Output :

output
Consider you want to update the dictionary with another dictionary

See the example below.

port1 = { 22: “SSH”, 23 : ‘Telnet’,80: “HTTP” }

port2 = { 53: “DNS”, 443: “HTTPS” }

port1.update( port2 )

print port1

Output:

{ 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

>>>

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 :

{1: ‘a’, 2: ‘b’, 3: ‘c’, 4: ‘d’}

Same above result can be achieved in one line.  See the example below.

list1 = [1 ,2, 3, 4]

list2 = [ ‘a’, ‘b’, ‘c’, ‘d’ ]

print dict(zip(list1,list2))

 

Output:

{1: ‘a’, 2: ‘b’, 3: ‘c’, 4: ‘d’}