Dictionary

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}

Accessing Values in Dictionary:

car = {"Company":"Mahindra", "Model":"XUV300", "Price":795000}
print(car["Model"])

XUV300

Updating Dictionary:

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}

Deleting Dictionary Element:

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

Properties of Dictionary Keys:
  1. 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.

  2. Keys must be immutable. This means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed.

Dictionary Methods:
  1. clear()
  2. copy()
  3. fromkeys()
  4. get()
  5. items()
  6. keys()
  7. pop()
  8. popitem
  9. setdefault()
  10. update()
  11. values()