Unordered Collection
Python provides two data structures for unordered collection: Dictionaries and Sets.
Dictionaries
Dictionary is an unordered set of key:value pairs in which the keys are unique. A pair of braces creates an empty dictionary: { }
Here is an example of dictionary with values:
country_codes = {'US':'United States', 'UK':'United Kingdom',
'CA':'Canada', 'MX':'Mexico'}
Sequences are indexed by range of numbers but dictionaries are indexed by keys. A key can be of any immutable type although using a string or a number is most common. Tuples can be used as keys as long as the elements of the tuples are immutable.
Here are some of common operations on Dictionaries
Operations | Example | Output | Comments |
---|---|---|---|
Get value given a key | country_codes['US'] | 'United States' | Dictionary keys are unique. Value can be any complex type including ordered or unordered collection |
Change value for a key | country_codes['US'] = 'USA' print(country_codes['US']) |
'USA' | Dictionaries are mutable so values can be changed |
Delete a key del | del country_codes['US'] print(country_codes) |
{'UK': 'United Kingdom', 'CA': 'Canada', 'MX': 'Mexico'} | A key/value pair is deleted |
Get a list of keys keys() | keys = list(country_codes.keys()) print(keys) |
['UK','CA', 'MX'] | You can check on the data type of keys by invoking print(type(keys)). You will notice that it is of type list |
Construct a dict from list of tuples | dict([('UK', 'United Kingdom'),('MX','Mexico')]) |
{'MX': 'Mexico', 'UK': 'United Kingdom'} | dict is one of the built in function |
Construct a dict using arguments | dict(UK = 'United Kingdom', MX ='Mexico') | {'MX': 'Mexico', 'UK': 'United Kingdom'} | Keys have to be strings for this to work |
Remove all elements clear() | state_codes = {'MI':'Michigan', 'IL':'Illinois'} state_codes.clear() print(state_codes) |
{} | |
Remove and get the element with specified key pop() | state_codes = {'MI':'Michigan', 'IL':'Illinois'} state_codes.pop('MI') print(state_codes) |
{'IL':'Illinois'} | This method returns the value of the popped key/value pair |
Remove last key/value pair popitem() | state_codes = {'MI':'Michigan', 'IL':'Illinois'} state_codes.popitem() print(state_codes) |
{'MI': 'Michigan'} | This method returns the popped key/value pair as a tuple |
Add a key/Value pair | country_codes['IN'] = 'India' print(country_codes) |
{'UK': 'United Kingdom', 'CA': 'Canada', 'IN':'India', MX': 'Mexico'} | If the key is not present a new Key/Value pair is added. Else the existing value for the key is replaced. |
Points to note
- If you try to access a key which is not present in the dictionary, KeyError is thrown