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.
capitals = print(type(capitals)) #output:
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:
d = <> # empty dictionary numNames= # int key, string value decNames= # float key, string value items= # tuple key, string value romanNums = # string key, int value
However, a dictionary with a list as a key is not valid, as the list is mutable:
But, a list can be used as a value.
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.
numNames = print(numNames) #output:
A dictionary can also be created using the 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.
numNames= print(numNames[1], numNames[2], numNames[3],) #output:One Two Three capitals = print(capitals["USA"], capitals["France"],) #output:Washington DC Paris #following throws an KeyError #print(capitals["usa"]) #print(capitals["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.
numNames= print(numNames.get(1), numNames.get(2),numNames.get(3)) capitals = print(capitals.get("USA"), capitals.get("France")) #following throws an KeyError #print(capitals.get("usa")) #print(capitals.get("Japan"))
Access Dictionary using For Loop
Use the for loop to iterate a dictionary in the Python script.
capitals = for key in capitals: print("Key = " + key + ", Value = " + capitalsGet dictionary name python)
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.
captains = print(captains) captains['India'] = 'Virat' captains['Australia'] = 'Paine' print(captains) #output:
If you use a new key and assign a value to it then it will add a new key-value pair into a dictionary.
captains = captains['SouthAfrica']='Plessis' print(captains) #output:
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 .
captains = print(captains) del captains['Australia'] # deletes a key-value pair print(captains) 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.
d1 = 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.
captains = 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:
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.
students= print(students) #, 2: , 3: > print(students[1]) # print(students[2]) # print(students[3]) #
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. |