FREE INTERACTIVE ONLINE COURSE

Python 3

FOR BEGINNERS


"The first Python course that simply amazed me. Very well explained and easy to understand." (Alexandru Cosmin)

"The best Python course in Romania." (Iulian Geană)


ALL REVIEWS
LESSON 16
PAGE 2 / 5
Dictionaries in Python
Home >>> Free Online Lessons, Python 3

We can use lists and tuples to create a dictionary!

It gets more interesting. You have already studied lists and tuples, and now we can use them to form a dictionary.

We can use a list of tuples, as in the following example:
Editor - lesson_16.py
       
Console/Output done
DETAILS

In this case, each object in the list passed as a parameter contains a tuple with two elements – the key and the associated value.

Notice that we used the dict() function/constructor to create the dictionary - a kind of explicit conversion. You will understand more when you study object-oriented programming.

Deleting/clearing a dictionary

To delete a dictionary, we use the del keyword, like "del dict1", as we are used to. If we want to clear it, we use the clear() method, specifically in our example: "dict1.clear()".

The in and not in operators

You already know how to use these, so test if certain keys are present or not in a dictionary, for example:

print('strong' in dict1)
print('cold' not in dict1)


Note, we search for information using keys (these are indexed) and not using the associated values! If we write: 'warm' in dict1, we will get the value False.
Proceed to the next page.
 home   list  CONTENTS   perm_identity   arrow_upward