Introduction to Dictionaries Definition : A dictionary is an unordered collection of key-value pairs. Syntax : { key1: value1, key2: value2,….} Example : my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
Common Dictionary Methods C lear() : Removes all elements from the dictionary Example : my_dict.clear () Copy() : Returns a shallow copy of the dictionary Example : new_dict = my_dict.copy ()
Accessing Elements get(key ): Returns the value for the specified key Example: value = my_dict.get ('name ') keys (): Returns a view object of all keys Example: keys = my_dict.keys ()
Modifying Dictionaries update () : Updates the dictionary with the specified key-value pairs Example : my_dict.update ({'age': 26 }) pop(key ) : Removes the element with the specified key Example : age = my_dict.pop ('age')
Iterating Through Dictionaries I tems() : Returns a view object of key-value pairs Example : for key, value in my_dict.items (): print(key, value )
Additional Methods P opitem () : Removes and returns the last inserted key-value pair . Example : last_item = my_dict.popitem () setdefault (key, default ) : Returns the value of the specified key. If the key does not exist, inserts the key with the specified value. Example : my_dict.setdefault ('country', 'USA')