Introduction to Python – Data Structures (Dictionaries)
You can follow along with the code from Github.
- The main operations on a dictionary (dict) are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del. If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.
- Keys can be any immutable type – strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples. If a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
You can follow along with the code flow from the Github.
- You can use different techniques when looping through dictionaries.
items() method – The key and corresponding value can be retrieved at the same time.
- enumerate() method – position index and corresponding value can be retrieved at the same time when looping through a sequence.
- zip() method – To loop over two or more sequences at the same time.
- reversed() method – loop over a sequence in reverse, first specify the sequence in a forward direction
- sorted() method – loop over a sequence in a sorted order which returns a new sorted list while leaving the source unaltered.
- set() method – Eliminates duplicate elements on a sequence. Set() can be using with sorted() method to loop over unique elements of the sequence in the sorted order.