Professional Documents
Culture Documents
ENEE 101
• myDictionary= {}
It creates an empty dictionary
3
Dictionary syntax
In this case we used a string type for the keys to allow leading
zeros.
4
Dictionary usage 1/4
• To add an item to a dictionary, use the syntax: dictionaryName[key] = value
• If the key is already in the dictionary, the preceding statement replaces the
value for the key (update the value corresponding the value).
• If the key is in the dictionary, the value for the key is returned. Otherwise, a
KeyError exception is raised.
5
Dictionary usage 2/4
The for loop iterates on the keys in the dictionary students (line 2).
students[key] returns the value for the key key (line 3).
You can find the number of the items in a dictionary by using len(dictionary).
For example:
7
Dictionary usage 4/4
You can use the in or not in operator to determine whether a key is in the
dictionary. For example:
You can use the == and != operators to test whether two dictionaries contain
the same items. For example:
You cannot use the comparison operators ( > , >= , <= , and < ) to compare
dictionaries because the items are not ordered. 8
Dictionary methods
9
Dictionary methods examples
10
Dictionary recap