Python Dictionary
Python Dictionary
Dictionaries are also collection/ containers and store data in form of key : value
pairs.
Dictionary contains many key : value pair, with each pair separated by comma
enclosed in curly brackets.
Characteristics of Dictionary –
d={
<key>: <value>,
<key>: <value>,
...
<key>: <value>
}
#empty dictionary
my_dict = {}
A dictionary uses keys to access data elements. Keys can be used either inside
square brackets [] or with the get() method.
Syntax –
Dictionary name[key]
If we use the square brackets [], KeyError is raised in case a key is not found in the
dictionary.
Dictionaries are mutable. We can add new items or change the value of existing
items using an assignment operator.
If the key is already present, then the existing value gets updated. In case the key
is not present, a new (key: value) pair is added to the dictionary.
teachers ['cs']='samir'
print(teachers)
teachers['math'] = 'rushi'
print(teachers)
Like other collections, dictionaries are also traversed using for loop.
>> math
science
gk
cs
Remember dictionaries are always accessed via its key. If you want to print the
values associated with each key use-
We can remove a particular item in a dictionary by using the del or pop command.
Del command
del teachers[‘math’] removes key : value pair associated with key ‘math’
The popitem() method can be used to remove and return an arbitrary (key,
value) item pair from the dictionary. All the items can be removed at once, using
the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary
itself.
Check existence of elements in Dictionary –
Syntax-
Key not in dictionary Returns True if key is not present otherwise false.
teachers ['cs']='samir'
teachers['math'] = 'rushi'
del teachers['math’]
print('math' in teachers)
print('civics'not in teachers)
Python Dictionary Methods
get() –This method return the value for the given key if present in the
dictionary. If not, then it will return None
Syntax : Dict.get(key, default=None)
items() method is used to return the list with all dictionary keys with values.
Syntax: dictionary.items()
keys() method list of all the keys in the dictionary in order of insertion in form of
list.
Syntax: dict.keys()
values() method returns a list of all the values available in a given dictionary.
Syntax: dictionary_name.values()
update() method updates the dictionary with the elements from another
dictionary object or from an iterable of key/value pairs.
Syntax: dict.update([other])
Dictionary1.update(Dictionary2)
print("Dictionary after updation:")
print(Dictionary1)
Dictionary1.update(Dictionary3)
print("Dictionary after updation:")
print(Dictionary1)
pop() remove the key : value pair from dictionary and returns the value to user.
Syntax – dict.pop(key)