CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

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

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

Defining a dictionary object

We use dict constructor to create the dictionary objects. Or we can use a 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 is entered in the curly braces; Python will create an empty dictionary object. Below are the examples to create an empty dictionary object.

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

Yes, curly braces are used to create sets. The only difference is, that 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 an 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 dictionary objects

Dictionary objects don’t support indexing directly. We can access elements from dictionary objects using its keys. For example,

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

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

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

Modifying elements from dictionary objects

We access the dictionary object elements through its keys. We use the same way to modify its elements. Here is an example:

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

This is a high-level overview of 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. Required fields are marked *

Scroll to top