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:
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.