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"}
print(type(capitals))  #output: <class 'dict'>

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. The dictionary class is dict.

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", 2:"Two"}
print(numNames)  #output: {1:"One", 2:"Two", 3:"Three"}

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

Example: dict() Constructor Method
emptydict = dict()

numdict = dict(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
numNames={1:"One", 2: "Two", 3:"Three"}
print(numNames[1], numNames[2], numNames[3],) #output:One Two Three

capitals = {"USA":"Washington DC", "France":"Paris", "India":"New Delhi"}
print(capitals["USA"], capitals["France"],)  #output:Washington DC Paris

#following throws an KeyError
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: Access Dictionary using get()
numNames={1:"One", 2: "Two", 3:"Three"}
print(numNames.get(1), numNames.get(2),numNames.get(3))

capitals = {"USA":"Washington DC", "France":"Paris", "India":"New Delhi"}
print(capitals.get("USA"), capitals.get("France"))

#following throws an KeyError

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'
print(captains)  #output: {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat'}

If you use a new key and assign a value to it then it will add a new key-value pair into a dictionary.

Example: Add New Key-Value Pair
captains = {"England":"Root", "India":"Dhoni"}
print(captains) #output: {'England': 'Root', '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 itself, use del dictionary_name.

Example: Delete a Key-Value Pair
captains = {'Australia': 'Paine', 'India': 'Virat', 'Srilanka': 'Jayasurya'}

del captains['Australia'] # deletes a key-value pair

del captains # delete dict object
#print(captains) #error

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'}

print(d1.keys()) #output: dict_keys(['name', 'age', 'marks', 'course'])
print(d1.values())  #output: 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'}

b = 'England' in captains
print(b) #True

b = 'India' in captains
print(b)  #True

b = 'France' in captains
print(b)  #False

Multi-dimensional Dictionary

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

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

Let's 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}
print(students) #{1: {'name': 'Steve', 'age': 25, 'marks': 60}, 2: {'name': 'Anil', 'age': 23, 'marks': 75}, 3: {'name': 'Asha', 'age': 20, 'marks': 70}}

print(students[1]) # {'name': 'Steve', 'age': 25, 'marks': 60}
print(students[2]) # {'name': 'Anil', 'age': 23, 'marks': 75}
print(students[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.

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.