Unordered Collection

In this lesson you will learn Dictionary and Set; the two data structures which are not considered a sequence.


Dictionary is a set of key:value pairs in which the keys are unique. A pair of braces creates an empty dictionary: { }

Although in the latest implementation of Python, dictionary maintains the order of insert, it is considered an implementation detail and should not be relied upon as it may change in the future as per the official documentation.

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'
'USA' Dictionaries are mutable so values can be changed
Delete a key del
del country_codes['US']
{'UK': 'United Kingdom', 'CA': 'Canada', 'MX': 'Mexico'} A key/value pair is deleted
Get a list of keys keys() keys = list(country_codes.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'}
Remove and get the element with specified key pop() state_codes = {'MI':'Michigan', 'IL':'Illinois'}
{'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'}
{'MI': 'Michigan'} This method returns the popped key/value pair as a tuple
Add a key/Value pair
country_codes['IN'] = 'India'
{'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

Dictionary Comprehension

Just like list, you can also creat a dictionary comprehension and here is an example

d1 = {'a':1, 'b': 5, 'c':10}

d2 = {v:k for k, v in d1.items()}


{1: 'a', 5: 'b', 10: 'c'}

In the above example, d2 contains d1 with key/value pair reversed

Getting the maximum key or value

You can get the largest key using the max function. This is straight forward. However if you want to get the key which holds the highest value then you would use the below expression

max(d1, key=d1.get)


results matching ""

    No results matching ""