Python-3.4.3/C3/Dictionaries/English

From Script | Spoken-Tutorial
Revision as of 13:21, 8 October 2018 by Nirmala Venkat (Talk | contribs)

Jump to: navigation, search
Visual Cue
Narration
Show Slide Containing title Welcome to the spoken tutorial on Dictionaries.
Show Slide

Objectives


In this tutorial, we will learn to,
  • Create dictionaries
  • Add and delete data from dictionaries
  • Retrieve data from dictionaries
  • Check for presence of keys and
  • Iterate over elements.


­Show Slide

System Specifications

To record this tutorial, I am using
  • Ubuntu Linux 16.04 operating system
  • Python 3.4.3 and
  • IPython 5.1.0


Show Slide

Pre-requisite


To practise this tutorial, you should know how to
  • use basic data types and operators

If not, see the relevant Python tutorials on this website.

Show Slide


Overview of dictionaries

First we will learn about dictionaries.


Dictionary is an unordered collection of items which has key:value pairs.


Dictionary is used to look up for a specific key and retrieve the corresponding value.

Show Slide


Overview of dictionaries

Keys are unique within a dictionary while values may not be.


The values of a dictionary can be of any data type.


But the keys must be of immutable data type such as strings, numbers or tuples.

Open the terminal Let us start ipython.


Open the terminal.

Type ipython3 and press Enter Type ipython3 and press Enter.


From here onwards, remember to press the Enter key after typing every command on the terminal.

empty = {}

Highlight curly braces

Let us start by creating an empty dictionary.


Type, empty is equal to open and close curly braces


Note that unlike lists, curly braces are used to define a dictionary.

student = {'name': 'raj',

'age': 16,

'gender': 'male',

'class': 10}

Now let us see how to create a non empty dictionary.


Type as shown.

Highlight the key value Note that,
  • Each key:value pair is separated by a comma,
  • Each key is separated from its value by a colon, and
  • The whole thing is enclosed in curly braces.

Here, we have defined four entries in the dictionary student.


The keys are name, age, gender, class.

Type, student Type, student to see its content.
Show Slide

Accessing elements

dictionary_name[key]

Next let us learn to access the dictionary elements.


The value of a dictionary can be accessed using the corresponding key.


The syntax is:

dictionary underscore name inside square brackets key

Type, print (student['name'])


Now let us access the value for the key ‘name’.


Type,

print inside brackets student inside square brackets inside single quotes name


As expected it printed the output as raj.

Type, print (student['class']) Now we will retrieve the value for the key ‘class’


Type,

print inside brackets student inside square brackets inside single quotes class


It displays the output as 10.

Type, student['height']


Highlight KeyError

If we try to access a value with a wrong key, we get an error.


Type, student inside square brackets inside single quotes height


The interpreter gave us the KeyError: 'height'


This is because, key 'height' is not present in the student dictionary.


This is about creating dictionaries.


<<PAUSE>>

Type, student['height'] = 6.2 Next, let us see how to add or delete items in a dictionary.

First let us add an element height to the dictionary student.


Type, student inside square brackets inside single quotes height is equal to 6.2

Type, student

Highlight 'height': 6.2

Let us now check the content of the dictionary.


Type, student


You can see that key-value 'height': 6.2 is added to the dictionary student.

Type, student['class'] = 11


Next let us modify the element class of the dictionary student.


Type,

student inside square brackets inside single quotes class is equal to 11

Type, student


Highlight class

Now, to check the content of the dictionary, type, student


As you can see, the value for class key is changed to 11 .

Type, del student['age'] Next let us learn to delete age from the dictionary student.


Type,

del student inside square brackets inside single quotes age

Type, student


Type, student


You can see that now key-value 'age': 16 is deleted from student.


<<PAUSE>>

Next let us see how to check whether a key is present in a dictionary.

For that we can use the method in.

Slide: Usage of in


The method in will return True if the key is found in the dictionary.


It will return False if key is not present.


Note that we can check only for the presence of the keys in dictionaries and not values.


Keys of a dictionary are not ordered.


Hence, slicing and striding are not valid on dictionaries.



Type, 'school' in student Let us try it with an example.

Type, inside single quotes school in student

We get False, since the key 'school' is not present in student.

Type, 'name' in student Type, inside single quotes name in student

We get True, as expected.

Show Slide

Retrieve keys and values


Next let us see how to retrieve keys and values of a dictionary.
  • Method keys() is used for getting a list of keys
  • Method values() is used for getting a list of values.


Type, student.keys()


Highlight the output

Now let us try the above methods with examples.


Type, student dot keys open and close brackets


It returns the list of keys of the dictionary student.

Type, student.values()


Highlight the output

Type,

student dot values open and close brackets


It returns the list of values of the dictionary student.

Type, student.items()


Highlight the output

Next let us see the items method.

Type,

student dot items open and close brackets


It returns a list of tuples of key-value pairs of the dictionary student.


The order of items of the list returned by keys(), values() and items() cannot be predicted.


In dictionaries, they are not in the order in which we inserted them.

Pause the video.


Try this exercise and then resume the video.

Show Slide

Exercise 1


Print the keys and values of the dictionary student one by one.


Hint: use the method items and for loop.

Switch to terminal Switch back to the terminal for the solution.
Type,

for key, val in student.items():

print (key, val)


Type as shown.


It displays the keys and values one by one.

Show Slide

Summary

This brings us to the end of this tutorial. Let us summarize.


In this tutorial, we have learnt to,

  • Create dictionaries
  • Access elements of a dictionary using keys
  • Add elements to a dictionary by assigning a value to a key


Show Slide

Summary

* Delete elements from a dictionary by using the function del
  • Retrieve the keys and values by using the methods keys() and values() respectively and
  • Iterate over elements of a dictionary using a for loop.


Show Slide

Self assessment questions

Here are some self assessment questions for you to solve
  1. Dictionary d is defined as shown:

How do you retrieve the value 'b'?

  1. Delete value 'b' from the dictionary d


Show Slide

Solution of self assessment questions


And the answers,
  1. d inside square brackets 2 gives the value 'b'
  2. del d inside square brackets 2 deletes the value ‘b’


Show Slide Forum Please post your timed queries in this forum.
Show Slide Fossee Forum Please post your general queries on Python in this forum.
Slide Textbook Companion FOSSEE team coordinates the TBC project.
Show Slide Acknowledgment Spoken Tutorial Project is funded by NMEICT, MHRD, Govt. of India. For more details, visit this website.
Previous slide This is Priya from IIT Bombay, signing off. Thanks for watching.

Contributors and Content Editors

Nancyvarkey, Nirmala Venkat, Priyacst