InterviewSolution
Saved Bookmarks
| 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: firstsecond third sunday monday tuesday Update key value in dictionary:
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')
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')
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} |
|