Python Dictionary with examples

Preview
You must first complete Python List with Examples | List in Python 3 before viewing this Lesson

Python Dictionary with examples

What is a dictionary?

A Dictionay is an unordered collections of elements in the form of  key: value pairs separated by commas within the pair of braces(curly brackets).

Example:

{1:’a’,2:’b’,3:’c’}


 Characteristics of a Dictionary

1. Unordered Set

Dictionary is an unordered set of key: value pairs i.e. Its values can contain references to any type of object .

2. Not a Sequence

Dictionary is not a sequence because it is unordered set of elements. Sequencs like list and string are indexed by a range of numbers. so they are ordered but a dictionary is indexed by keys not numbers so it is unordered collection.

3. Indexed by Keys, Not Numbers

Dictionaries are indexed by keys. A key can be any non mutable type.  So we can  use strings  numbers as well as tuples as keys as they are non mutable.  

Values in a dictionary can be of any type.

For example dictionary dict1 has keys of different immutable types:

>>> dict1={0:”numeric key”,”str”:”string key”,(4,5):”tuple key”}

>>> dict1
{0: ‘numeric key’, ‘str’: ‘string key’, (4, 5): ‘tuple key’}

4. Keys must be Uniqe

Keys within a dictionary must  be unique. As keys are used to identify values in a dictionary ,there cannot be duplicate keys in a dictionary.

Example:

>>> dict2={5:”number”, “a”:”string”, 5:”numeric”}

>>> dict2
{5: ‘numeric’, ‘a’: ‘string’}

If there are duplicate keys, key appearing later will be taken in the output.

5. Mutable

Dictionaries are also mutable. We can change the value of a paricular key using the assignment statement as:

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

Example

>>> dict1={0: ‘numeric key’, ‘str’: ‘string key’, (4, 5): ‘tuple key’}

>>> dict1[‘str’]=”STRING”

>>> dict1
{0: ‘numeric key’, ‘str’: ‘STRING’, (4, 5): ‘tuple key’}

Value of key ‘str’ has been updated with ‘STRING’

f . Internally Stored as Mappings

The key: value pairs in a dictionary are associated with one another with some internal function (called hash-function). This way of linking is called mapping.



1. Creating a Dictionary

To create a dictionary, we need to put key:value pairs within curly braces.

Syntax for creating a dictionary:

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

Elements of dictionary has two parts namely key followed by colon (:) again followed by value. These key-value pairs are separated from each other by commas.

Example:

Teachers ={“Lovejot”:”Computer science”,”Munish”:”Science”,   “Vijay”:”Punjabi”,”Sunil”:”SST”}

Braces (curly brackets) specify the start and end of the dictionary.

There are four key: value pairs. Following table shows the key- value relationships in above dictionary.

Key–value pair    KeyValue
“Lovejot”:”Computer science”LovejotComputer
“Munish”:”Science”MunishScience
“Vijay”:”Punjabi”VijayPunjabi
“Sunil”:”SST”SunilSST

Example

>>> Teachers ={“Lovejot”:”Computer science”, “Munish”:”Science”, “Vijay”:”Punjabi”, “Sunil”:”SST” }

 >>> Teachers
{‘Lovejot’: ‘Computer science’,  ‘Munish’: ‘Science’,  ‘Vijay’: ‘Punjabi’,  ‘Sunil’: ‘SST’}

Keys of a dictionary must be of immutable types like string,number etc.

If we try to give a mutable type as key, Python will give error

>>> dict={[1]:”abc”}

Traceback (most recent call last):
File “<pyshell#22>”, line 1, in <module>
dict={[1]:”abc”}
TypeError: unhashable type: ‘list’

TypeError:unhashable type means that we have tried to assign a key with mutable type and Python dictionaries do not allow this.


2 . Initializing a Dictionary

We can initialize a dictionary by writing key:value pairs collectively separated by commas and enclosed in curly braces.

Example:

Employee ={‘name’:’john’,’salary’:10000,’age’:24}

3. Creating an empty Dictionary

There are two ways to create an empty dictionary:

(i) By giving dictionary contents in empty curly braces as:

 Employee ={}

(ii) By using function dict() as:

Employee=dict()

Employee is an empty dictionary with no elements.

4. Creating a dictionary from name and value Pairs

We can create a new dictionary initialized from specified set of keys and values. There are multiple ways to provide keys and values to dict() function.

(a) Specify Key :Value pairs as keyword arguments to dict() function

Keys and values are passed to dict() function in pair by using assignment operator

Example:

>>> Employee =dict(name=’Anil’,salary=20000,age=25)

>>> Employee
{‘name’: ‘Anil’, ‘salary’: 20000, ‘age’: 25}

 (b) Specify comma-separated key:value pairs

To specify values in key: value pairs, we need to enclose them in curly braces while using dict() function.

Example:

>>> Employee =dict({‘name’:’Anil’,’salary’:20000,’age’:25})

>>> Employee
{‘name’: ‘Anil’, ‘salary’: 20000, ‘age’: 25}

(c) Specify keys separately and corresponding values separately.

Keys and values are enclosed separately in parentheses and are given as arguments to zip() function ,which is given as an argument to dict() function.

Example

>>> Employee =dict(zip((‘name’,’salary’,’age’),(‘Anil’,20000,25)))

>>> Employee
{‘name’: ‘Anil’, ‘salary’: 20000, ‘age’: 25}

In above example, ‘name’ is associated with value ‘Anil’, ‘salary’ is associated with value 20000 and age is associated with value 25

(d) Specify Key:Value Pairs separately in form of sequences.

In this method, one list or tuple is passed to function dict() as argument. This argument contains lists /tuple of individual key: value pairs in the dictionary.

Example 1:

>>> Employee= dict([[‘name’,’John’],[‘salary’,10000],[‘age’,24]])

>>> Employee
{‘name’: ‘John’, ‘salary’: 10000, ‘age’: 24}

 Example 2:

>>> Employee= dict(((‘name’,’John’),(‘salary’,10000),(‘age’,24)))

>>> Employee
{‘name’: ‘John’, ‘salary’: 10000, ‘age’: 24}

 

5. Accessing Elements of a Dictionary

To access elements from a dictionary, we use the keys defined in the key: value pairs.

Syntax

<dictionary-name>[<key>]

To access the value corresponding to key “Lovejot “ in Teachers dictionary, we can write Teacher[“Lovejot”]

Python will return

Computer Science

Similarly, following statement

>>>print (“Vijay teaches”,Teacher[‘Vijay’])

Will give output as:

Vijay teaches Punjabi

We can simply write the name of dictionary within the pair of parenthesis after print() to display entire dictionary

Example

>>>>>> vowels={“Vowel1″:”a”,”Vowel2″:”e”,”Vowel3″:”I”,”Vowel4″:”o”, “Vowel5″:”u”}

 >>> vowels
{‘Vowel1’: ‘a’, ‘Vowel2’: ‘e’, ‘Vowel3’: ‘I’, ‘Vowel4’: ‘o’, ‘Vowel5’: ‘u’}

 >>> vowels[‘Vowel3’]
I

 Python gives error If we try to access a key that doesn’t exist Consider the

Example

>>> vowels[‘Vowel6’]

Traceback (most recent call last):
File “<pyshell#7>”, line 1, in <module>
vowels[‘Vowel6’]
KeyError: ‘Vowel6’

Above error means that we can’t access the value of a particular key that does not exist in dictionary.


6. Traversing a dictionary

Traversing means accessing and processing each element of a collection. We can use looping statements to traverse a dictionary.

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

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

The loop variable <item>will be stored the keys of <Dictionary>one by one which we can use inside the body of the for loop.

Example:

We have a dictionary dict1 as

Python Code
dict1={5:”number”, “a”:”string”, True:”Boolean”}
for key in dict1:
   print (key,”:”,dict1[key])
Output
5 : number
a : string
True : Boolean

Description of above program

The loop variable key will be assigned the keys of the Dictionary dict1,one at a time.

Using the loop variable which has been assigned one key at a time, the corresponding value is shown along with the key using print statement as

print(key,”:”,dict1[key])

During first iteration loop variable key will be assigned 5 so the key 5 and its value “number”will be printed.

In second  iteration, key  will get “a” and its value “string“will be shown.

Similarly in third iteration, key will get True and its value “Boolean will be shown”.


7. View all Keys of a dictionary

To view all the keys in a dictionary in one go, we can use dictionary>.keys() function.

Example:

>>> dict1={5:”number”, “a”:”string”, True:”Boolean”}

 >>> dict1.keys()
dict_keys([5, ‘a’, True])

 

8. View all values of a dictionary

To view all the values in a dictionary in one go, we can use dictionary>.values() function.

Example

>>> dict1={5:”number”, “a”:”string”, True:”Boolean”}

 >>> dict1.values()
dict_values([‘number’, ‘string’, ‘Boolean’])



 9. Adding Elements to Dictionary

We can add new elements to a dictionary using assignment operator but the key being added should not exist in dictionary and must be uniqe.

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>

Example

>>> Employee={‘name’: ‘John’, ‘salary’: 10000, ‘age’: 24}

 >>> Employee[‘Dept’]=’Sales’  
#Add new element  with key=’Dept’, value=’Sales’

 >>> Employee
{‘name’: ‘John’, ‘salary’: 10000, ‘age’: 24, ‘Dept’: ‘Sales’}

 10. Nesting of Dictionary

We can also take one dictionary as an element of another dictionary. This process of storing a dictionary inside another dictionary is called nesting of dictionaries. We can store a dictionary as a value only not as a key.

11. Updating Existing Elements in a Dictionary

We can change value of an existing key using assignment operators as:

Dictionary>[<key>]=<value>

Example

>>> dict1={0: ‘numeric key’, ‘str’: ‘string key’, (4, 5): ‘tuple key’}

 >>> dict1[‘str’]=”STRING”

 >>> dict1
{0: ‘numeric key’, ‘str’: ‘STRING’, (4, 5): ‘tuple key’}

The key must exist in the dictionary otherwise new entry will be added to the dictionary.



12. Deleting Elements from a dictionary

There are two methods for deleting elements from a dictionary.

(i) To delete a dictionary element using del command

We can use del command to delete an element of dictionary as.

del<dictionary>[<key>]

Example:

>>> Employee={‘name’: ‘John’, ‘salary’: 10000, ‘age’: 24}

 >>> del Employee[‘name’]
#Dictionary element with key ‘name’ gets deleted.

 >>> Employee
{‘salary’: 10000, ‘age’: 24}

(i) To delete a dictionary element using pop() function

We can use pop() function to delete an element of dictionary as.

<dictionary>.pop(<key>)

Example

>>> Employee={‘name’: ‘John’, ‘salary’: 10000, ‘age’: 24}

 >>> Employee.pop(‘name’)
‘John’

 >>> Employee
{‘salary’: 10000, ‘age’: 24}

The pop () method deletes the key: value pair for specified key but also returns the corresponding value.

If we try to delete key which does not exist, the Python returns error.

pop()method allows us to specify message to be shown when the given key does not exist. It can be done as:

<dictionary>.pop(<key>,<Error-message>)

Example

>>> Employee.pop(‘new’,’Not Found’)
‘Not Found’



13. Check for Existence of a Key

We can use membership operators in and not in with dictionaries. But they can check for the existence of keys only

To check for existence of existing key in a dictionary, we can write statement as

<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 given key is not present in the dictionary otherwise False.

Example

>>> Employee={‘name’: ‘John’, ‘salary’: 10000, ‘age’: 24}

 >>> ‘name’ in Employee
True

 >>> ‘name’ not in Employee
False




Lesson tags: dictionary in python3, operations on dictionary in python 3, python dictionary, python dictionary with examples
Back to: Python Programming Tutorial