Dictionary In Python-

  • 1) This collection is used to store the value in the form of key and value pair like HashMap in Java.
  • 2) It maintains the insertion order.
  • 3) Values can be duplicate, but keys should be unique.
  • 4) New value will replace the existing value when we store the key which is already present in dictonary.
  • 5) It will override the value of existing key.
  • 6) Each key’s are separated from its value by a colon (:)
  • 7) The set of key and value pair are separated by commas(,)
  • 8) Whole dictonary is closed in curly braces.
  • 9) An empty dictionary with no items is written with simply two curly braces, like this: {}
  • 10) Generally values of a dictionary are not holding any sorting order, however, the keys should be of an immutable type object like strings, numbers, or tuples.
  • 11) Dictionaries concept is also available in other programming languages as well with name of “associative arrays” which means that items are indexed by a scope of numbers, python dictionaries are indexed by keys.
  • 12) Keys can be any immutable type e.g. strings and numbers can generally be keys.
  • 13) Dictionary is alterable this means we can add, change and delete items but doesn’t permit duplicates, meaning that we can’t create different items with the same key.

How To Access Dictionary In Python

Ex-

dict = {'Name': 'Rohit', 'Age': 17, 'Class': 'First'}

print(dict['Name']) - Rohit
print(dict['Age']) - 17
  • Keys() –

    It will return all the keys from the dictionary object.

  • Values() –

    It will return all the values from the dictionary object.

  • Items() –

    It will return the list of all dictionary element.

  • Update() –

    It is used to update the dictionary object.

Ex-

d = {10:'A', 20:'B', 30:'C'}
print(d)

d1={10: 'A', 20: 'A'}
print(d1)

d2 ={10: 'A', 10:'B'}
print(d2)  # {10: 'B'}

d3 = {10: 'A', "10": 34.56}
print(d3)  # {10: 'A', "10": 34.56}

d4 = {10:None}
print(d4)  # {10:None}
d5 = {10: 'A', 20: 'B', 30: 'C'}
print(d5.keys()) #dict_keys([10, 20, 30])
print(d5.values()) # dict_values(['A', 'B', 'C'])
print(d5.items()) # dict_items([(10, 'A'), (20, 'B'), (30, 'C')])

Updating Dictionary

  • – You can also update an existing record by adding a new record or keyword pair, or by deleting an existing record.
d5.update({40:'D'}) #Updating the dictionary by adding new pair
print(d5)

d5.update({40:'E'}) #Updating the dictionary by updating the existing pair
print(d5)

del d5[10] #Removing entry with key '10'
print(d5)

for k,v in d5.items():
    print(k, "-", v)

Ouptut-

	20 - B
	30 - C
	40 - E
  • # If you will try to delete the key which is not present in dictionary then below error will appear-
  • del d5[10] #Traceback (most recent call last):
  • File “D:/Sachin/Python_BK/SAB103/Test.py”, line 22, in
  • del d5[10]
  • KeyError: 10
Menu