Notes Chapter 9 Dictionaries

Introduction

• Python provides us various options to store multiple values under one variable name.

• Dictionaries is also a collection like a string, list and tuple.

• It is a very versatile data type.

• There is a key in it with a value.(Key:value)

• Dictionaries are mutable data types and it is an unordered collection in the form of key:value

• In List, index of a value is important whereas in dictionary, key of a value is important.

Dictionary Creation

• To create a dictionary, it is needed to collect pairs of key:value in “{ }”.

<dictionary-name>={ <key1>:<value1>,<key2>:<value2>,<key3>:<value3>. . . }

Example:
teachers={“Rajeev”:”Math”, “APA”:”Physics”,”APS”:”Chemistry:”SB”:”CS”}

In above given example :

Notes Chapter 9 Dictionaries

• Some examples of Dictionary are-

Dict1= { } # this is an empty dictionary without any element.

DayofMonth= { January”:31, ”February”:28, ”March”:31, ”April”:30, ”May”:31, ”June”:30, ”July”:31, ”August”:31, ”September”:30, ”October”:31, ”November”:30, ”December”:31}

FurnitureCount = { “Table”:10, “Chair”:13, “Desk”:16, “Stool”:15, “Rack”:15 }

– By above examples you can easily understand about the keys and their values.
– One thing to be taken care of is that keys should always be of immutable type.

Note: Dictionary is also known as associative array or mapping or hashes .

–Keys should always be of immutable type.
–If you try to make keys as mutable, python shown error in it. For example-

Notes Chapter 9 Dictionaries

Accessing a Dictionary

• To access a value from dictionary, we need to use key similarly as we use an index to access a value from a list.

• We get the key from the pair of Key: value.

teachers={“Rajeev”:”Math”, “APA”:”Physics”,”APS”:”Chemistry:”SB”:”CS”}

• If we execute following statement from above example-

Notes Chapter 9 Dictionaries

• We have selected key “Rajeev” and on printing it, Math got printed. Another example-

Notes Chapter 9 Dictionaries

Traversal of a Dictionary

• To traverse a Dictionary, we use for loop. Syntax is-

Notes Chapter 9 Dictionaries

• To access key and value we need to use keys() and values().for example-

Notes Chapter 9 Dictionaries

– d.keys( ) function will display only key.
– d.values ( ) function will display value only.

Features of Dictionary

1. Unordered set: dictionary is a unordered collection of key:value pairs.

2. Not a sequence: like list, string and tuple , it is not a sequence because it is a collection of unordered elements whereas a sequence is a collection of indexed numbers to keep them in order.

3. Keys are used for its indexing because according to Python key can be of immutable type. String and numbers are of immutable type and therefore can be used as a key. Example of keys are as under-

Notes Chapter 9 Dictionaries

4. Keys should be unique : Because keys are used to identify values so they should be unique.

5. Values of two unique keys can be same.

6. Dictionary is mutable hence we can change value of a certain key. For this, syntax is-

Notes Chapter 9 Dictionaries

7. Internally it is stored as a mapping. Its key:value are connected to each other via an internal function called hash-function**. Such process of linking is knows as mapping.

**Hash-function is an internal algorithm to link a and its value.

Working with Dictionary

• Here we will discuss about various operation of dictionary like element adding, updation, deletion of an element etc. but first we will learn creation of a dictionary.

Dictionary initialization- For this we keep collection of pairs of key:value separated by comma (,) and then place this collection inside “{ }”.

Notes Chapter 9 Dictionaries

Addition of key: value pair to an empty dictionary. There are two ways to create an empty dictionary-
1.Employee = { }
2.Employee = dict( )
After that use following syntax-

Notes Chapter 9 Dictionaries
Notes Chapter 9 Dictionaries

Creation of a Dictionary with the pair of name and value: dict( ) constructor is used to create dictionary with the pairs of key and value. There are various methods for this-

I. By passing Key:value pair as an argument:

Notes Chapter 9 Dictionaries

The point to be noted is that here no inverted commas were placed in argument but they came automatically in dictionary.

II. By specifying Comma-separated key:value pair-

Notes Chapter 9 Dictionaries

III. By specifying Keys and values separately:

Notes Chapter 9 Dictionaries

IV. By giving Key: value pair in the form of separate sequence:

Notes Chapter 9 Dictionaries

Adding an element in Dictionary

following syntax is used to add an element in Dictionary-

Notes Chapter 9 Dictionaries

Nesting in Dictionary

look at the following example carefully in which element of a dictionary is a dictionary itself.

Notes Chapter 9 Dictionaries

Updation in a Dictionary

following syntax is used to update an element in Dictionary-

<dictionary>[<ExistingKey>]=<value>

Notes Chapter 9 Dictionaries

WAP to create a dictionary containing names of employee as key and their salary as value.

Notes Chapter 9 Dictionaries

Output

Notes Chapter 9 Dictionaries

Deletion of an element from a Dictionary

Following two syntaxes can be used to delete an element form a Dictionary. For deletion, key should be there otherwise python will give error.

1. del <dictionary>[<key>]- it only deletes the value and does not return deleted value.

Notes Chapter 9 Dictionaries

2. <dictionary>.pop(<key>) it returns the deleted value after deletion.

Notes Chapter 9 Dictionaries

Detection of an element from a Dictionary

Membership operator is used to detect presence of an element in a Dictionary.

1. <key> in <dictionary> it gives true on finding the key otherwise gives false.

2. <key> not in <dictionary> it gives true on not finding the key otherwise gives false.

Notes Chapter 9 Dictionaries

Pretty Printing of a Dictionary

To print a Dictionary in a beautify manner, we need to import json module. After that following syntax of dumps ( ) will be used.

json.dumps(<>,indent=)

Notes Chapter 9 Dictionaries

Program to create a dictionary by counting words in a line

Notes Chapter 9 Dictionaries

Dictionary Function and Method

1. len( ) Method : it tells the length of dictionary.

Notes Chapter 9 Dictionaries

2. clear( ) Method : it empties the dictionary.

Notes Chapter 9 Dictionaries

3. get( ) Method : it returns value of the given key.

Notes Chapter 9 Dictionaries

4.items( ) Method : it returns all items of a dictionary in the form of tuple of (key:value).

Notes Chapter 9 Dictionaries

5. keys( ) Method : it returns list of dictionary keys.

Notes Chapter 9 Dictionaries

6.values( ) Method : it returns list of dictionary values.

Notes Chapter 9 Dictionaries

7.Update ( ) Method: This function merge the pair of key:value of a dictionary into other dictionary. Change and addition in this is possible as per need. Example-

Notes Chapter 9 Dictionaries

In the above given example, you can see that change is done in the values of similar keys whereas dissimilar keys got joined with their values.

Notes Chapter 9 Dictionaries

Related Posts

error: Content is protected !!