1.

Python Dictionaries

Answer»

Dictionaries in Python are equivalent to Maps in C++/JAVA. They are used to store data in key-value pairs.

Printing key and values in dictionaries:

To print the keys of the dictionary, use the .keys() method and to print the values, use .values() method.

dict = {'first' : 'sunday', 'second' : 'monday', 'third' : 'tuesday'}
# dict.keys() method will print only the keys of the dictionary
for key in dict.keys():
print(key)
# dict.values() method will print only the values of the corressponding keys of the dictionary
for value in dict.values():
print(value)

Output:

first
second
third
sunday
monday
tuesday

Update key value in dictionary:


  • Update key value which is not present in dictionary:
    We can update a key value in a dictionary by accessing the key withing [] and setting it to a value.
dict = {'first' : 'sunday', 'second' : 'monday', 'third' : 'tuesday'}
for item in dict.items():
print(item)
dict['fourth'] = 'wednesday'
for item in dict.items():
print(item)
Output:
('first', 'sunday')
('second', 'monday')
('third', 'tuesday')
('first', 'sunday')
('second', 'monday')
('third', 'tuesday')
('fourth', 'wednesday')

  • Update key value which is present in the dictionary:
    We can update a key value in a dictionary, when the key is present in the exact same way as we update a key, when the key is not present in the dictionary.
dict = {'first' : 'sunday', 'second' : 'monday', 'third' : 'tuesday'}
for item in dict.items():
print(item)
dict['third'] = 'wednesday'
for item in dict.items():
print(item)
Output:
('first', 'sunday')
('second', 'monday')
('third', 'tuesday')
('first', 'sunday')
('second', 'monday')
('third', 'wednesday')

  • Delete key-value pair from dictionary:
    We can delete a key-value pair from a dictionary using the del keyword followed by the key value to be deleted enclosed in [].
dict = {'first' : 'sunday', 'second' : 'monday', 'third' : 'tuesday'}
for item in dict.items():
print(item)
del dict['third']
for item in dict.items():
print(item)
Output:
('first', 'sunday')
('second', 'monday')
('third', 'tuesday')
('first', 'sunday')
('second', 'monday')

Merging 2 dictionaries

We can merge 2 dictionaries into 1 by using the update() method.

dict1 = {'first' : 'sunday', 'second' : 'monday', 'third' : 'tuesday'}
dict2 = {1: 3, 2: 4, 3: 5}
dict1.update(dict2)
print(dict1)
Output:
{'first': 'sunday', 'second': 'monday', 'third': 'tuesday', 1: 3, 2: 4, 3: 5}


Discussion

No Comment Found