Introduction to Python – Dictionary

Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable and do not allow duplicates.

Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}. Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Example

Create and print a dictionary:thisdict =&nbsp;{<br>&nbsp;&nbsp;
"brand":&nbsp;"Ford",<br>&nbsp;&nbsp;"model":
&nbsp;"Mustang",<br>&nbsp;&nbsp;"year":&nbsp;1964<br>}<br>print(thisdict)

Dictionary Items

Dictionary items are ordered, changeable, and does not allow duplicates. Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

Example

Print the "brand" value of the dictionary:thisdict =&nbsp;
{<br>&nbsp;&nbsp;"brand":&nbsp;"Ford"
,<br>&nbsp;&nbsp;"model":&nbsp;"Mustang",<br>&nbsp;&nbsp;"
year":&nbsp;1964<br>}<br>print(thisdict["brand"])<br><a target="_blank"

Ordered or Unordered?

As of Python version 3.7, dictionaries are ordered. dictionaries are unordered. When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change. Unordered means that the items does not have a defined order, you cannot refer to an item by using an index.

Changeable

Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.

Duplicates Not Allowed

Dictionaries cannot have two items with the same key:

Example

Duplicate values will overwrite existing values:thisdict = {<br>  "brand": "Ford",<br>  "model": "Mustang",<br>  "year": 1964,<br>  "year": 2020<br>}<br>print(thisdict)

Dictionary Length

To determine how many items a dictionary has, use the len() function:

Example

Print the number of items in the dictionary:

print(len(thisdict))

Accessing Values in Dictionary

To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example −

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']

When the above code is executed, it produces the following result −

dict['Name']:  Zara
dict['Age']:  7

If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows −

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Alice']: ", dict['Alice']

When the above code is executed, it produces the following result −

dict['Alice']:
Traceback (most recent call last):
   File "test.py", line 4, in <module>
      print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'

Change Values

You can change the value of a specific item by referring to its key name:

Example

Change the "year" to 2018:thisdict = {<br>  "brand": 
"Ford",<br>  "model": "Mustang",<br>  "year": 1964<br>}<br>
thisdict["year"] = 2018<br>

Updating Dictionary

You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example −

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry

print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']

When the above code is executed, it produces the following result −

dict['Age']:  8
dict['School']:  DPS School

Adding Items

Adding an item to the dictionary is done by using a new index key and assigning a value to it:

Example

thisdict =&nbsp;{<br>&nbsp;&nbsp;"brand":&nbsp;
"Ford",<br>&nbsp;&nbsp;"model":&nbsp;"Mustang",<br>&nbsp;&nbsp;"year":
&nbsp;1964<br>}<br>thisdict["color"] =&nbsp;"red"<br>print(thisdict)

Delete Dictionary Elements

You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.

To explicitly remove an entire dictionary, just use the del statement. Following is a simple example −

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear();     # remove all entries in dict
del dict ;        # delete entire dictionary

print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']

This produces the following result. Note that an exception is raised because after del dict dictionary does not exist any more −

dict['Age']:
Traceback (most recent call last):
   File "test.py", line 8, in <module>
      print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable

Note − del() method is discussed in subsequent section.

Properties of Dictionary Keys

Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys. There are two important points to remember about dictionary keys −

(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. For example −

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print "dict['Name']: ", dict['Name']

When the above code is executed, it produces the following result −

dict['Name']:  Manni

(b) Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like [‘key’] is not allowed. Following is a simple example −

#!/usr/bin/python

dict = {['Name']: 'Zara', 'Age': 7}
print "dict['Name']: ", dict['Name']

When the above code is executed, it produces the following result −

Traceback (most recent call last):
   File "test.py", line 3, in <module>
      dict = {['Name']: 'Zara', 'Age': 7};
TypeError: unhashable type: 'list'

Python – Loop Dictionaries

Loop Through a Dictionary

You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

Example

Print all key names in the dictionary, one by one:

for x in thisdict:<br>  print(x)

Example

Print all values in the dictionary, one by one:

for x in thisdict:<br>  print(thisdict[x])

Example

You can also use the values() method to return values of a dictionary:

for x in thisdict.values():<br>  print(x)

Example

You can use the keys() method to return the keys of a dictionary:

for x in thisdict.keys():<br>  print(x)

Example

Loop through both keys and values, by using the items() method:

for x, y in thisdict.items():<br>  print(x, y)

Python – Copy Dictionaries

Copy a Dictionary

You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2. There are ways to make a copy, one way is to use the built-in Dictionary method copy().

Example

Make a copy of a dictionary with the <code>copy()</code> method:thisdict = {<br>  "brand": "Ford",<br>  "model": "Mustang",<br>  "year": 1964<br>}<br>mydict = thisdict.copy()<br>print(mydict)

Another way to make a copy is to use the built-in function dict().

Example

Make a copy of a dictionary with the&nbsp;<code>dict()</code>&nbsp;function:thisdict =&nbsp;{<br>&nbsp;&nbsp;"brand":&nbsp;"Ford",<br>&nbsp;&nbsp;"model":&nbsp;"Mustang",<br>&nbsp;&nbsp;"year":&nbsp;1964<br>}<br>mydict&nbsp;=&nbsp;dict(thisdict)<br>print(mydict)

Python – Nested Dictionaries

Nested Dictionaries

A dictionary can contain dictionaries, this is called nested dictionaries.

Example

Create a dictionary that contain three dictionaries:myfamily = {<br>  "child1" : {<br>    "name" : "Emil",<br>    "year" : 2004<br>  },<br>  "child2" : {<br>    "name" : "Tobias",<br>    "year" : 2007<br>  },<br>  "child3" : {<br>    "name" : "Linus",<br>    "year" : 2011<br>  }<br>}

Or, if you want to add three dictionaries into a new dictionary:

Example

Create three dictionaries, then create one dictionary that will contain the other three dictionaries:child1 = {<br>&nbsp;&nbsp;"name"&nbsp;:&nbsp;"Emil",<br>&nbsp;&nbsp;"year"&nbsp;:&nbsp;2004<br>}<br>child2 = {<br>&nbsp;&nbsp;"name"&nbsp;:&nbsp;"Tobias",<br>&nbsp;&nbsp;"year"&nbsp;:&nbsp;2007<br>}<br>child3 = {<br>&nbsp;&nbsp;"name"&nbsp;:&nbsp;"Linus",<br>&nbsp;&nbsp;"year"&nbsp;:&nbsp;2011<br>}
myfamily = {<br>&nbsp;&nbsp;"child1"&nbsp;: child1,<br>&nbsp;&nbsp;"child2"&nbsp;: child2,<br>&nbsp;&nbsp;"child3"&nbsp;: child3<br>}

Built-in Dictionary Functions & Methods

Python includes the following dictionary functions −

Sr.No.Function with Description
1cmp(dict1, dict2)Compares elements of both dict.
2len(dict)Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
3str(dict)Produces a printable string representation of a dictionary
4type(variable)Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.

Introduction to Python – Dictionary
Show Buttons
Hide Buttons