Dictionary
Python - Dictionary
Section titled “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.
key:value
The following declares a dictionary object.
capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"}print(type(capitals)) #output: <class 'dict'>capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"} print(type(capitals)) #output: <class 'dict'>Try it
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.
capitals````:``dict
A number, string or tuple can be used as key. Hence, the following dictionaries are also valid:
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`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`Try it However, a dictionary with a list as a key is not valid, as the list is mutable:
dict_obj = {["Mango","Banana"]:"Fruit", ["Blue", "Red"]:"Color"}dict_obj = {["Mango","Banana"]:"Fruit", ["Blue", "Red"]:"Color"}
But, a list can be used as a value.
dict_obj = {"Fruit":["Mango","Banana"], "Color":["Blue", "Red"]}dict_obj = {"Fruit":["Mango","Banana"], "Color":["Blue", "Red"]}Try it
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 = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One", 2:"Two"}print(numNames) #output: {1:"One", 2:"Two", 3:"Three"}numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One", 2:"Two"} print(numNames) #output: {1:"One", 2:"Two", 3:"Three"}Try it
A dictionary can also be created using the dict() constructor method.
dict()
emptydict = dict()
numdict = dict(I='one', II='two', III='three')`emptydict = dict()
numdict = dict(I=‘one’, II=‘two’, III=‘three’)`Try it
Access Dictionary
Section titled “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={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#print(capitals["usa"])#print(capitals["Japan"])`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
#print(capitals[“usa”])
#print(capitals[“Japan”])[Try it](/codeeditor?cid=python-3z7uupb4f) 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. usa“USA 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. [get()](/python/dict-get)None`
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#print(capitals.get("usa"))#print(capitals.get("Japan"))`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 #print(capitals.get(“usa”)) #print(capitals.get(“Japan”))`Try it
Access Dictionary using For Loop
Section titled “Access Dictionary using For Loop”Use the for loop to iterate a dictionary in the Python script.
capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"}
for key in capitals: print("Key = " + key + ", Value = " + capitals[key])`capitals = {“USA”:“Washington D.C.”, “France”:“Paris”, “India”:“New Delhi”}
for key in capitals: print(“Key = ” + key + ”, Value = ” + capitals[key])`Try it
Key = 'USA', Value = 'Washington D.C.' Key = 'France', Value = 'Paris' Key = 'India', Value = 'New Delhi'Key = 'USA', Value = 'Washington D.C.' Key = 'France', Value = 'Paris' Key = 'India', Value = 'New Delhi'
Update Dictionary
Section titled “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 = {"England":"Root", "Australia":"Smith", "India":"Dhoni"}print(captains)
captains['India'] = 'Virat'captains['Australia'] = 'Paine'print(captains) #output: {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat'}`captains = {“England”:“Root”, “Australia”:“Smith”, “India”:“Dhoni”} print(captains)
captains[‘India’] = ‘Virat’ captains[‘Australia’] = ‘Paine’ print(captains) #output: {‘England’: ‘Root’, ‘Australia’: ‘Paine’, ‘India’: ‘Virat’}`Try it 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 = {"England":"Root", "India":"Dhoni"}captains['SouthAfrica']='Plessis'print(captains) #output: {'England': 'Root', 'India': 'Virat', 'SouthAfrica': 'Plessis'}captains = {"England":"Root", "India":"Dhoni"} captains['SouthAfrica']='Plessis' print(captains) #output: {'England': 'Root', 'India': 'Virat', 'SouthAfrica': 'Plessis'}Try it
Deleting Values from a Dictionary
Section titled “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.
pop()popitem()del dictionary_name
captains = {'Australia': 'Paine', 'India': 'Virat', 'Srilanka': 'Jayasurya'}print(captains)
del captains['Australia'] # deletes a key-value pairprint(captains)
del captains # delete dict object#print(captains) #error`captains = {‘Australia’: ‘Paine’, ‘India’: ‘Virat’, ‘Srilanka’: ‘Jayasurya’} print(captains)
del captains[‘Australia’] # deletes a key-value pair print(captains)
del captains # delete dict object #print(captains) #error`Try it
Retrieve Dictionary Keys and Values
Section titled “Retrieve Dictionary Keys and Values”The keys() and values() methods return a view objects containing keys and values respectively. keys()values()
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'])`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’])`Try it
Check Dictionary Keys
Section titled “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.
in``not in
captains = {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'Srilanka': 'Jayasurya'}
b = 'England' in captainsprint(b) #True
b = 'India' in captainsprint(b) #True
b = 'France' in captainsprint(b) #False`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`Try it
Multi-dimensional Dictionary
Section titled “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}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.
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}`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}[Try it](/codeeditor?cid=python-3z7uwamcz) 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. studentd1d2d3students[1]“d1`
Built-in Dictionary Methods
Section titled “Built-in Dictionary Methods”dict.clear()dict.copy()dict.fromkeys()dict.get()dict.items()dict.keys()dictionary view objectdict.pop()dict.popitem()dict.setdefault()dict.update()dict.values()dictionary view object