Dictionary is an unordered set of key:value pairs. Dictionaries are indexed by keys, which can be any immutable type, strings and numbers can always be keys.
Creating Dictionary:
car = {"Company":"Mahindra", "Model":"XUV300", "Price":795000}
print(car)
{'Company': 'Mahindra', 'Model': 'XUV300', 'Price': 795000}
car = {"Company":"Mahindra", "Model":"XUV300", "Price":795000}
print(car["Model"])
XUV300
You can update a dictionary by adding a new entry or modifying the values.
car = {"Company":"Mahindra", "Model":"XUV300", "Price":795000}
car["Model"] = "Scorpio"
car["KMPL"] = 15
print(car)
{'Company': 'Mahindra', 'Model': 'Scorpio', 'Price': 795000, 'KMPL': 15}
You can remove individual dictionary elements using del statement.
car = {"Company":"Mahindra", "Model":"XUV300", "Price":795000}
print(car)
del car["Price"]
print(car)
{'Company': 'Mahindra', 'Model': 'XUV300', 'Price': 795000}
{'Company': 'Mahindra', 'Model': 'XUV300'}
More than one entry per key is not allowed. This means no duplicate key is allowed. When duplicate keys are encountered during assignment, the last assignment is to be considered.
Keys must be immutable. This means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed.