Python Dictionary

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.

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:

** = {}**

OR

** = dict()**

The syntax to create a Python dictionary with items is:

** = { 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, Mohit, two 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 “”, line 1, in 

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]

‘SSH’

>>> port1[53]

‘DNS’

>>> port1[67]

Traceback (most recent call last):

File “”, line 1, in 

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” )

‘DNS’

>>> 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”)

‘SSH’

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

‘Key not found’

>>>

Has_key()

The has_key() method returns True and False statements.

>>> 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 a Python Dictionary

You can delete a single element of the dictionary as well the 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 “”, line 1, in 

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 :

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

47341080L

>>> id(port2)

47374680L

>>>

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

Output:

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

Thank you for reading !

Python Bigdata tutorial dictionaries

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc.. You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like __init__, __call__, __str__ etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Python Modules Tutorial - Python Tutorial for Beginners

This Edureka session on Python Modules Tutorial will help you understand the concept of modules in python, why, and how we can use modules in Python.

Tutorial: Web Scraping with Python Using Beautiful Soup

Web scraping allows us to extract information from web pages. In this tutorial, you'll learn how to perform web scraping with Python and BeautifulSoup.The internet is an absolutely massive source of data. Unfortunately, the vast majority if it isn’t available in conveniently organized CSV files for download and analysis. If you want to capture data from many websites, you’ll need to try web scraping.

Python Dictionary

A dictionary in python is unordered, changeable and indexed. It is unordered because it does not keep track of the order of data inserted. It is changeable because you can change the values of keys.