Python Dictionaries Tutorial

Contents show


Python Dictionaries

Python dictionaries are a collection of some key-value pairs. Dictionaries are mutable, unordered collections with elements in the form of a key : value pairs that associate keys to values.

1. Creating a Dictionary

To create a dictionary, you need to include the key : value pairs in curly braces as per following syntax :

<dictionary-name> = {<key> : <value>, <key> : <value> . . .}

Following is an example by the name teachers that stores the names of teachers as keys and the subjects being taught by them as values of respective keys.

teachers = {"Dimple" : "Computer Science", "Karen" : "Socillogy", "Harpreet" : "Mathematics", "Saban" : "Legal Studies"}

Notice that

  • the curly brackets mark the beginning and end of the dictionary.
  • each entry (key : value) consists of a pair separated by a colon – the key and corresponding value is given by writing colon (:) between them,
  • the key-value pairs are separated by commas (,).

Internally, dictionaries are indexed (i.e., arranged) on the basis of keys.

2. Accessing Elements of a Dictionary

In dictionaries, the elements are accessed through the keys defined in the key : value pairs, as per the syntax shown below :


Thus to access the value for key defined as “Karen” in above declared teachers dictionary, you will write :

>>> teachers["Karen"]

and Python will return


Attempting to access a key that does’t exist causes an error.

Consider the following statement that is trying to access a non-existent key (13) from dictionary teachers.

>>> teachers["Kushal"]
teachers KeyError : 13

In Python dictionaries, the elements(key : value pairs) are unordered ; one cannot access elements as per specific order.

Accessing Keys or Values Simultaneously

To see all the keys in a dictionary in one go, you may write .keys( ) and to see all values in one go, you may write .values( ), as shown below :

>>> d = {"colour1" : "red", "colour2" : "blue", "colour3" : "green"}
>>> d.keys( )
['colour1', 'colour2', 'colour3']
>>> d.values( )
['red', 'blue', 'green']

3. Characteristics of a Dictionary

Dictionaries like Lists are mutable and that is the only similarity they have with lists.

Otherwise, dictionaries are different type of data structure with following characteristics :

(a) A dictionary is a unordered set of key : value pairs.

(b) Unlike the string, list and tuple, a dictionary is not a sequence because it is unordered set of elements.

(c) Dictionaries are indexed by keys and its keys must be of any non-mutable type.

(d) Each of the keys within a dictionary must be unique.

(e) Like lists, dictionaries are also mutable. We can change the value of a certain key “in place” using the assignment statement as per syntax :

<dictionary>[<key] = <value>

4. Dictionary Operations

In this section, we shall briefly talk, about various operations possible on Python dictionaries.

4.1 Traversing a Dictionary

Traversing of a collection means accessing and processing each element of it.

The for loop makes it easy to traverse or loop over the items in a dictionary, as per following syntax :

for <item> in <Dictionary> :
      process each item here

Consider following example that will illustrate this process. A dictionary namely d1 is defined three keys – a number, a string, a tuple of integers.

d1 = {5 : "number", /
         "a" : "string", /
         (1, 2) : "tuple"}

To traverse the above dictionary, you can write for loop as :

for key in d1 :
      print(key, ":", d1[key])

The above loop will produce the output as shown below :

a : string
(1, 2) : tuple
5 : number

4.2 Adding Elements to Dictionary

You can add new elements (key : value pair) to a dictionary using assignment as per the following syntax. BUT the key being added must not exist in dictionary and must be unique. If the key already exists, then this statement will change the value of existing key and no new entry will be added to dictionary.

<dictionary>[<key>] = <value>

Consider the following example :

>>> Worker = {'name' : 'rahul', 'salary' : 10000, 'age' : 24}
>>> Worker['dept'] = 'sales'
>>> Worker
{'salary' : 10000, 'dept' : 'sales', 'age' : 24, 'name' : 'rahul'}

4.3 Updating Existing Elements in a Dictionary

Updating an element is similar to what we did just now. That is, you can change value of an existing key using assignment as per following syntax :

<dictionary>[<key>] = <value>

Consider the following example :

>>> Worker = {'name' : 'rahul', 'salary' : 10000, 'age' : 24}
>>> Worker['salary'] = 20000
>>> Worker
{'salary' : 20000, 'age' : 24, 'name' : 'rahul'}

But make sure that thek ey must exist in the dictionary, otherwise new entry will be added to dictionary.
Using this technique of adding key : value pairs, you can create dictionaries interactively at runtime by accepting input from user.

4.4 Deleting Elements from a Dictionary

There are two methods for deleting elements from a dictionary.

(i) To delete a dictionary element or a dictionary entry, i.e., a key:value pair, you can use del command. The syntax for doing so is as given below :

Consider the following example :
>>> Worker
{'name' : 'rahul', 'salary' : 10000, 'age' : 24}
>>> del Worker['age']
>>> Worker
{'name' : 'rahul', 'salary' : 10000}

But with del statement, the key that you are giving to delete must exist in the dictionary, otherwise Python will return an error. See below :

>>> del Worker['new']
del Worker['new']
KeyError : 'new'

(ii) Another method to delete elements from a dictionary is by using Pop( ) method as per following syntax :


The pop( ) method will not only delete the key:value pair for mentioned key but also return the corresponding value.
Consider the following code example

>>> Worker
{'name' : 'rahul', 'salary' : 10000, 'age' : 24}
>>> Worker.pop('age')
>>> Worker
{'salary' : 10000, 'name' : 'john'}

If you try to delete a key which does not exist, the Python returns error. See below :

>>> Worker.pop('new')
KeyError : 'new'

However, pop( ) method allows you to specify what to display when the given key does not exist, as per following syntax :

<dictionary>.pop(<key>, <in-case-of-error-show-me>)

For example :

>>> Woker.pop('new', "Not Found")
'Not Found'

4.5 Checking for Existence of a Key

Usual membership operators in and not in work with dictionaries as well. But they can check for the existence of keys only. You may use them as per syntax given below :

<key> in <dictionary>
<key> not in <dictionary>
  • The in operator will return True if the given key is present in the dictionary, otherwise False.
  • The not in operator will return True if the given key is not present in the dictionary, otherwise False.

Consider the following example :

>>> Worker = {'name' : 'rahul', 'salary' : 10000, 'age' : 24}
>>> 'age' in Worker
>>> 'rahul' in Worker
>>> 'rahul' not in Worker
>>> 'age' not in Worker

5. Dictionary Functions and Methods

5.1 The len( ) method

This method returns length of the dictionary, i.e., the count of elements (key:value pairs) in the dictionary. The syntax to use this method is given below :



>>> Worker = {'name' : 'rahul', 'salary' : 10000, 'age' : 24}
>>> len(Worker)

5.2 The clear( ) method

This method removes all items from the dictionary and the dictionary becomes empty dictionary post this method.

<dictionary>.clear( )


>>> Worker = {'name' : 'rahul', 'salary' : 10000, 'age' : 24}
>>> Worker.clear( )
{ }

Note :

The clear( ) removes all the elements of a dictionary and makes it empty dictionary while del statement removes the complete dictionary as an object. After del statement with a dictionary name, that dictionary object no more exists, not even empty dictionary.

5.3 The get( ) method

python dictionary get

With this method, you get the item with the given key, similar to dictionary[key]. If the key not present, Python will give error.

<dictionary>.get(key, [default])


>>> Worker 
{'name' : 'rahul', 'salary' : 10000, 'age' : 24}
>>> Worker.get('age')

5.4 The items( ) method

This method returns all of the items in the dictionary as a sequence of (key, value) tuples. Note that these are returned in no particular order.

<dicitonary>.items( )


Worker = {'name' : 'rahul', 'salary' : 10000, 'age' : 24}
myList = Worker.items( )
for x in myList :

The adjacent code gives output as :

('salary', 10000)
('age', 24)
('name', 'rahul')

5.5 The keys( ) method

This method returns all of the keys in the dictionary as a sequence of keys(in form of a list). Note that these are returned in no particular order.

<dictionary>.keys( )


>>> Worker 
{'name' : 'rahul', 'salary' : 10000, 'age' : 24}
>>> Worker.keys( )
['name', 'salary', 'age']

5.6 The values( ) method

This method returns all the values from the dictionary as a sequence (a list). Note that these are returned in no particular order.

<dictionary>.values( )


>>> Worker 
{'name' : 'rahul', 'salary' : 10000, 'age' : 24}
>>> Worker.values( )
[rahul, 10000, 24]

5.6 The update( ) method

This method merges key : value pair from the new dictionary into the original dictionary, adding or replacing as needed. The items in the new dictionary are added to the old one and override any items already there with the same keys.
The syntax to use this method is given below :



>>> employee1 = {'name' : 'john', 'salary' : 10000, 'age' : 24}
>>> employee2 = {'name' : 'Diya', 'salary' : 54000, 'dept' : 'sales'}
>>> employee1.update(employee2)
>>> employee1
{'salary' : 54000, 'dept' : 'sales', 'name' : 'Diya', 'age' : 24}
>>> employee2
{'salary' : 54000, 'dept' : 'sales', 'name' : 'Diya'}


Dictionaries in Python Example

Dictionaries in Python Class 11

Python Tuples

Python lists

visit : Python tutorial 2021

FAQ :-

Q 1. What is a Python dictionary?

Ans. In python,a Dictionary is unordered,unchangeable and doesn’t allow duplicate elements and it contains a key and the key’s value.Dictionary in python is declared by opening and closing curly brackets {}.

Q 2. Can you have a list of dictionaries in Python?

Ans. Yes, you can have a list of dictionaries in Python. you can access each dictionary as an element of a list using an index.

Q 3. How do you create a dictionary in Python?

Ans. To create a Python dictionary, we need to pass a sequence of items inside curly braces {} , and separate them using a comma (,). Each item has a key and a value expressed as a “key:value” pair. The values can belong to any data type and they can repeat, but the keys must remain unique.

Q 4. Why are dictionaries useful in Python?

Ans. Why do we need dictionaries? As a dictionary, keeps the elements in key-value mapping format and internally uses hashing for it; therefore, we can get a value from the dictionary by its key very quickly. In best cases, its complexity is O(1), whereas, in the worst case, its complexity can be O(n).

Q 5. How do you create a nested dictionary?

Ans. Addition of elements to a nested Dictionary can be done in multiple ways. One way to add a dictionary in the Nested dictionary is to add values one be one, Nested_dict[dict][key] = ‘value’ . Another way is to add the whole dictionary in one go, Nested_dict[dict] = { ‘key’: ‘value’} .

Q 6. Can you put a list in a dictionary python?

Ans. You can convert a Python list to a dictionary using the dict. fromkeys() method, a dictionary comprehension, or the zip() method. The zip() method is useful if you want to merge two lists into a dictionary.

Q 7. Can you sort a dictionary python?

Ans. To sort a dictionary by value in Python you can use the sorted() function. Python’s sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. Dictionaries map keys to values, creating pairs that hold related data.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *