Python Mapping Types

The mapping objects are used to map hash table values to arbitrary objects. In python there is mapping type called dictionary. It is mutable.

The keys of the dictionary are arbitrary. As the value, we can use different kind of elements like lists, integers or any other mutable type objects.

Some dictionary related methods and operations are −

Method len(d)

The len() method returns the number of elements in the dictionary.

Operation d[k]

It will return the item of d with the key ‘k’. It may raise KeyError if the key is not mapped.

Method iter(d)

This method will return an iterator over the keys of dictionary. We can also perform this taks by using iter(d.keys()).

Method get(key[, default])

The get() method will return the value from the key. The second argument is optional. If the key is not present, it will return the default value.

Method items()

It will return the items using (key, value) pairs format.

Method keys()

Return the list of different keys in the dictionary.

Method values()

Return the list of different values from the dictionary.

Method update(elem)

Modify the element elem in the dictionary.

Example Code

Live Demo

myDict = {'ten' : 10, 'twenty' : 20, 'thirty' : 30, 'forty' : 40}

#create items from the key-value pairs

myDict.update({'fifty' : 50})


{'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40}
['ten', 'twenty', 'thirty', 'forty']
[10, 20, 30, 40]
[('ten', 10), ('twenty', 20), ('thirty', 30), ('forty', 40)]
{'ten': 10, 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50}