Python 14 Dictionaries
Python 14 Dictionaries
A mutable and unordered collection of key : value pairs enclosed in curly brackets, Where each key :
value pair is separated by comma.
Note:
{ } → Empty Dictionary
{ 1 : ’a’, 2 : ’b’, 3 : ’c’ }
Creating a dictionary
Syntax:
Example
language = { ‘Python’ : ‘Gudio Van Rossum’, ‘C’ : ‘Dennis Ritchie’, ‘Java’ : ‘James Gosling’, ‘C++’ :
‘Bjarne Stroustrup’}
Dictionary elements are accessed through leys defined in key : value pair.
Syntax:
dictionary_name[key]
Example
Note: Attempting to access a key that doesn’t exist will cause an error
Traversing a dictionary
Adding a new key : value pair is done via assignment operation. If a key is already present then its
corresponding value will be updated otherwise a new key : value pair will be added to the dictionary.
Syntax:
Example:
Deleting an element from dictionary
• del statement
• pop(key) method
del statement
Syntax:
del dictionary_name[key] → will delete the specified key : value pair. If the key is not found then an
error will be raised.
Example:
pop(key) method:
Syntax:
dictionary_name.pop(key) → will delete the specified key value pair and returns it. If the key is not
present an error is raised.
Clearing the contents of dictionary:
clear() method is used to remove all key : value pair in a dictionary. Here an empty dictionary is
obtained after applying the operation.
Syntax:
dictionary_name.clear()
Example:
len() → returns the length of the dictionary i.e., number of key : value pair it has.
Syntax: len(dictionary_name)
Example:
Getting keys of the dictionary
syntax: dictionary_name.keys()
Example:
Syntax: dictionary_name.values()
Example:
Syntax: dictionary_name.items()
Example:
Getting a value corresponding to a key
get(key) → This method takes key as an input and returns the corresponding value. If a non-existing
key is passed it returns None
Syntax: dictionary_name.get(key)
Example:
update() → This method merges key : value pairs from the new dictionary into the existing one. The
item in the new dictionary is added to the old one and overrides any item already there with the
same keys.
Syntax: dictionary_name.update(another_dicitionary_name)
Example: