Last updated
Last updated
Dictionary (Associative Array, map, symbol table) is a data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection.
Common Operations:
Adding a pair
Removing a pair
Modify an existing pair
Lookup of a value associated with a particular key
Aside: This concept is an introduction to concepts similar to: hash table and search trees
Each item in a dictionary is a key, value pair.
Keys
Keys are unique address for a dictionary value’s location
Key Properties:
Must be immutable (strings, numbers, tuples, frozenset)
Unique; therefore, two same key values cannot exist in a single dictionary
NEWEST CREATED ITEM with a duplicate KEY superceeds the previous declaration
Values
Values of a dictionary within a key can be any data type.
Updating a Dictionary
We can modify existing values by referencing the key
We can add new values to a dictionary by creating a new key
We can overwrite a value at an existing key by referencing and recreating the value for it
Deletion with Dictionary
We can delete a key hence deleting the value connected to the key
We can empty out the entire dictionary
We can delete the dictionary (uncommonly used)
Membership
We can use the in and not in operators to check if a key exists in a dictionary
Built-in Functions’ Interactions w/ Dictionaries
Duplicate a Dictionary and Copy Keys Only
To help power this awesome data structure, it has good set of methods for us to use.
Let A and B be a dictionary
A.keys() –> Returns a sequence of keys/addresses in A
A.values() –> Returns a sequence of item values in A
A.items() –> Returns a sequence of key,item pairs in A
A.get(address) –> Returns the item value at address
A.update(B) –> Extends A with the dictionary of key,value pairs of B
We will be taking advantage of three iteration methods
iterating the keys
iterating the values
iterating the key, value pairs by unpacking
We can turn other data types to dictionaries.
Also similar to lists, tuples, and sets, dictionaries also support comprehension.
Note:
We must specify where the keys are and where the values.