Over a million developers have joined DZone.

Python Dictionary

DZone's Guide to

Python Dictionary

In this post, we'll introduce the concept of Python dictionaries, what they are used for, and how to work with dictionaries in your Python code.

· Big Data Zone ·
Free Resource

Hortonworks Sandbox for HDP and HDF is your chance to get started on learning, developing, testing and trying out new features. Each download comes preconfigured with interactive tutorials, sample data and developments from the Apache community.

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

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

The syntax to create an empty dictionary is:

< variable-name > = {}


< variable-name > = dict()

The syntax to create a Python dictionary with items is:

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

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

Features of a Python Dictionary

  1. The key of a Python dictionary cannot be changed.
  2. The value of a key can be changed.
  3. The ordering is not significant. The order in which you have entered the items in the dictionary, may not be the same order in which the items are returned. 

Features of a Python Dictionary: Key

Keys are unique to the Python dictionary they are used in. We cannot assign the same key twice.

Let's look at an example.

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

>>> dict1

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


In the above example, we used the same key, Mohittwo times, although the program is not giving any errors. But, y can see the most recent key replaced the old one.

intfloat, and string can be used as a key. The tuple which does not contain any lists 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 that if a tuple with a list is used then the interpreter will throw an error.

Features of a Python Dictionary: Value

The value can be repeated.

You can store anything in the value.

Y can add and update the value from the dictionary.

Let's 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.

Accessing the Values of Python Dictionary

Like Python lists, indexing does not exist in Python dictionaries. 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]


>>> port1[53]


>>> 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 an error. In order to tackle this problem, the get() method is used. See the example below.

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


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

‘not found’


Instead of an error, a customized message gets printed.

Different Ways to Check for the Existence of a Key

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

You have already seen the get() method.

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


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

‘Key not found’



The has_key() method returns True and False statements.

>>> port1.has_key(22)


>>> port1.has_key(24)



By Using in Operator

>>> if 22 in port1:

…     print “Key found”


Key found


Delete Elements of a Python Dictionary

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


>>> 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 a for Loop

In order to iterate over the Python dictionary, we used the items() or iteritems() method. The items() method returns 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 the items() method works just like the iteritems() method.

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

for k, v in port1.items():

    print k, ” : ” ,v

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


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

So far you have learned about Python dictionary creation, deleting an item, adding an item, and updating items. Let's 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)


>>> id(port2)



In the above example, a new dictionary, port2 , which is a copy of port1, has been created.

The memory addresses of both the dictionaries are different.

Practical Example

Let us create a dictionary using two 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’}

The same 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))


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

Hortonworks Community Connection (HCC) is an online collaboration destination for developers, DevOps, customers and partners to get answers to questions, collaborate on technical articles and share code examples from GitHub.  Join the discussion.

python ,dictionaries ,big data ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}