Python – Mapping Types – dict – A walk through with dictionary objects

Python mapping objects are mutable. Currently dictionary is the only mapping objects available in Python. Dictionary objects contains key and value pairs. Dictionary keys are non-mutable and we can add mutable or non-mutable objects as values.

Defining a dict object

We use dict constructor to create the dictionary objects. Or we can use comma (“,”) separated key and value pairs within the curly braces. Key and value pairs should be separated by a colon (“:”); that means, key: value pair in the curly braces.

If no arguments are passed to the dict constructor or nothing entered in the curly braces; Python will create an empty dictionary object. Below are the examples to create an empty dictionary objects.

>>> d1 = dict()
>>> d1
{}
>>> d2 = {}
>>> d2
{}

Yes, curly braces are used to create sets. The only difference is, when we create dictionary objects, we pass key: value pairs whereas for sets we just pass the values. But if we do not pass any elements within the curly braces; Python will create an empty dictionary object.

Dictionary objects are key: value pairs. When you pass them without curly braces, through the dict constructor; you must assign a value to the key using the symbol (“=”) and the key: value pairs should be separated by commas (“,”). Here is the example:

>>> d = dict(a="apple", b="banana")
>>> d
{'a': 'apple', 'b': 'banana'}
>>>

And also keys should be unique in dictionary objects. If you attempt to give duplicate keys; Python will throw the Error.

>>> d = dict(a="apple", a="avocado")
  File "<stdin>", line 1
SyntaxError: keyword argument repeated
>>>

Accessing elements from dict objects

Dictionary objects doesn’t support indexing directly. We can access elements from dictionary objects using it’s keys. For example,

>>> d
{'a': 'apple', 'b': 'banana'}
>>> d['a']
'apple'
>>>

If we attempt to give invalid key to access the value; Python throws the Error. Here is the example:

>>> d['c']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'c'
>>>

Modifying elements from dict objects

We access the dictionary objects elements through it’s keys. We use the same way to modify it’s elements. Here is the example:

>>> d['a'] = "avocado"
>>> d
{'a': 'avocado', 'b': 'banana'}
>>>

This is an high level overview on dictionary objects.  We discuss more in my upcoming Articles.

/Shijit/

Python – Mapping Types – dict – A walk through with dictionary objects

Leave a Reply

Your email address will not be published.

Scroll to top