Python - Dictionary

The dictionary is an unordered collection that contains key:value pairs separated by commas inside curly brackets. Dictionaries are optimized to retrieve values when the key is known.

The following declares a dictionary object.

Example: Dictionary
capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"}

Above, capitals is a dictionary object which contains key-value pairs inside { }. The left side of : is a key, and the right side is a value. The key should be unique and an immutable object. A number, string or tuple can be used as key. Hence, the following dictionaries are also valid:

Example: Dictionary Objects
d = {} # empty dictionary

numNames={1:"One", 2: "Two", 3:"Three"} # int key, string value

decNames={1.5:"One and Half", 2.5: "Two and Half", 3.5:"Three and Half"} # float key, string value

items={("Parker","Reynolds","Camlin"):"pen", ("LG","Whirlpool","Samsung"): "Refrigerator"} # tuple key, string value

romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5} # string key, int value

However, a dictionary with a list as a key is not valid, as the list is mutable:

Error: List as Dict Key
dict_obj = {["Mango","Banana"]:"Fruit", ["Blue", "Red"]:"Color"}

But, a list can be used as a value.

Example: List as Dictionary Value
dict_obj = {"Fruit":["Mango","Banana"], "Color":["Blue", "Red"]}

The same key cannot appear more than once in a collection. If the key appears more than once, only the last will be retained. The value can be of any data type. One value can be assigned to more than one key.

Example: Unique Keys
>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"}
>>> numNames
{1:"One", 2:"Two", 3:"Three"}

The dict is the class of all dictionaries, as shown below.

Example: Distinct Type
>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"}
>>> type(numNames)
<class 'dict'>

A dictionary can also be created using the dict() constructor method.

Example: dict() Constructor Method
>>> emptydict = dict()
>>> emptydict
>>> numdict = dict(I='one', II='two', III='three')
>>> numdict
{'I': 'one', 'II': 'two', 'III': 'three'}

Access Dictionary

Dictionary is an unordered collection, so a value cannot be accessed using an index; instead, a key must be specified in the square brackets, as shown below.

Example: Get Dictionary Values
>>> capitals = {"USA":"Washington DC", "France":"Paris", "India":"New Delhi"}
'Washington DC'
>>> capitals["France"]
>>> capitals["usa"]  # Error: Key is case-sensitive
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
KeyError: 'usa'
>>> capitals["Japan"] # Error: key must exist
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
KeyError: 'Japan'
Keys are case-sensitive. So, usa and USA are treated as different keys. If the specified key does not exist then it will raise an error.

Use the get() method to retrieve the key's value even if keys are not known. It returns None if the key does not exist instead of raising an error.

Example: Get Dictionary Values
>>> capitals = {"USA":"Washington DC", "France":"Paris", "Japan":"Tokyo", "India":"New Delhi"}
>>> capitals.get("USA")
'Washington DC'
>>> capitals.get("France")
>>> capitals.get("usa")
>>> capitals.get("Japan")

Access Dictionary using For Loop

Use the for loop to iterate a dictionary in the Python script.

Example: Access Dictionary Using For Loop
capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"}

for key in capitals:
    print("Key = " + key + ", Value = " + capitals[key]) 
Key = 'USA', Value = 'Washington D.C.'
Key = 'France', Value = 'Paris'        
Key = 'India', Value = 'New Delhi'

Update Dictionary

As mentioned earlier, the key cannot appear more than once. Use the same key and assign a new value to it to update the dictionary object.

Example: Update Value of Key
>>> captains = {"England":"Root", "Australia":"Smith", "India":"Dhoni"}
>>> captains['India'] = 'Virat'
>>> captains['Australia'] = 'Paine'
>>> captains
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat'}

Use a new key and assign a value to it. The dictionary will show an additional key-value pair in it.

Example: Add New Key-Value Pair
>>> captains['SouthAfrica']='Plessis'
>>> captains
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'SouthAfrica': 'Plessis'}

Deleting Values from a Dictionary

Use the del keyword, pop(), or popitem() methods to delete a pair from a dictionary or the dictionary object itself. To delete a pair, use its key as a parameter. To delete a dictionary object, use its name.

Example: Delete Key-Value
>>> captains = {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'Srilanka': 'Jayasurya'}
>>> del captains['Srilanka'] # deletes a key-value pair
>>> captains
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat'}
>>> del captains # delete dict object
>>> captains
NameError: name 'captains' is not defined

The NameError indicates that the dictionary object has been removed from memory.

Retrieve Dictionary Keys and Values

The keys() and values() methods return a view objects containing keys and values respectively.

Example: keys()
>>> d1 = {'name': 'Steve', 'age': 21, 'marks': 60, 'course': 'Computer Engg'}
>>> d1.keys()
dict_keys(['name', 'age', 'marks', 'course'])
>>> d1.values()
dict_values(['Steve', 21, 60, 'Computer Engg'])

Check Dictionary Keys

You can check whether a paritular key exists in a dictionary collection or not usng the in or not in keywords, as shown below. Note that it only checks for keys not values.

Example: Check Keys
>>> captains = {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'Srilanka': 'Jayasurya'}
>>> 'England' in captains
>>> 'India' in captains
>>> 'France' in captains
>>> 'USA' not in captains

Multi-dimensional Dictionary

Let's assume there are three dictionary objects, as below:

Example: Dictionary
>>> d1={"name":"Steve","age":25, "marks":60}
>>> d2={"name":"Anil","age":23, "marks":75}
>>> d3={"name":"Asha", "age":20, "marks":70}

Let us assign roll numbers to these students and create a multi-dimensional dictionary with roll number as key and the above dictionaries at their value.

Example: Multi-dimensional Dictionary
>>> students={1:d1, 2:d2, 3:d3}
>>> students
{1: {'name': 'Steve', 'age': 25, 'marks': 60}, 2: {'name': 'Anil', 'age': 23, 'marks': 75}, 3: {'name': 'Asha', 'age': 20, 'marks': 70}}<

The student object is a two-dimensional dictionary. Here d1, d2, and d3 are assigned as values to keys 1, 2, and 3, respectively. The students[1] returns d1.

Example: Access Multi-dimensional Dictionary
>>> students[1]
{'name': 'Steve', 'age': 25, 'marks': 60}
>>> students[1]['age']

Built-in Dictionary Methods

Method Description
dict.clear() Removes all the key-value pairs from the dictionary.
dict.copy() Returns a shallow copy of the dictionary.
dict.fromkeys() Creates a new dictionary from the given iterable (string, list, set, tuple) as keys and with the specified value.
dict.get() Returns the value of the specified key.
dict.items() Returns a dictionary view object that provides a dynamic view of dictionary elements as a list of key-value pairs. This view object changes when the dictionary changes.
dict.keys() Returns a dictionary view object that contains the list of keys of the dictionary.
dict.pop() Removes the key and return its value. If a key does not exist in the dictionary, then returns the default value if specified, else throws a KeyError.
dict.popitem() Removes and return a tuple of (key, value) pair from the dictionary. Pairs are returned in Last In First Out (LIFO) order.
dict.setdefault() Returns the value of the specified key in the dictionary. If the key not found, then it adds the key with the specified defaultvalue. If the defaultvalue is not specified then it set None value.
dict.update() Updates the dictionary with the key-value pairs from another dictionary or another iterable such as tuple having key-value pairs.
dict.values() Returns the dictionary view object that provides a dynamic view of all the values in the dictionary. This view object changes when the dictionary changes.