DEV Community

Cover image for Python Dictionaries and their operations
Surya Teja
Surya Teja

Posted on

Python Dictionaries and their operations

The whole point of programming concludes to one inevitable out-coming i.e., we write instructions to manipulate/control DATA.

Python provides many data structures to store data, Dictionary is one among them which store the data as a key-value pair. According to official documentation, there are many definitions but, I find the below definition easy to understand.

Dictionaries are a type of data structures, which are indexed by keys. It can also be defined as an unordered set of key: value pairs. Immutable(not dynamic) types like strings and numbers can always be keys.*

Basic operations on Dictionaries

As mentioned in the first point, python provides no.of ways to manipulate/control data. Below mentioned are a few basic methods used in dictionaries.

Loops on Dictionaries

On dictionaries, python provides three basic methods to loop through the items
of the dictionary.

  • dict.items()
  • dict.keys()
  • dict.values()

Other methods on Dictionaries

Python also provides methods which can be really helpful in reducing the size of
code by using reusable modules.

Comparing dictionaries

The compare method cmp() is used to compare length of two dictionaries. The method returns 0 if both dictionaries are equal, 1 if dic1 > dict2 and -1 if dict1 < dict2.

    >>> Boys = {'sunny': 26,'Chary':18,'Robin':25}
    >>> Girls = {'pari':22} 
    >>> print(cmp(Girls, Boys))
Enter fullscreen mode Exit fullscreen mode

get(key[, default]) Method

Return the value for key if the key is in the dictionary, else default. If
default is not given, it defaults to None so that this method never raises a KeyError.

get() is a very useful function as we don’t need to loop through the dictionary items to check whether a certain key is present in the dictionary. For nested dictionaries, it reduces a lot of pain to loop and checks as well as it makes the code more readable.

    # dict.get( key, default )
    >>> Boys.get('sunny')
    >>> Boys.get('surya', 'Not Found')
    'Not Found'
    >>> Boys.get('surya')
Enter fullscreen mode Exit fullscreen mode

Merging two dictionaries to one dictionary

There are many methods to merge two dictionaries into a single dictionary. Using the multiple arguments ‘**’ operator we can achieve this.

      >>> x = {'a': 1, 'b': 2}
      >>> y = {'b': 3, 'c': 4}
      >>> z = {**x, **y}
          {'a': 1, 'b': 3, 'c': 4}
Enter fullscreen mode Exit fullscreen mode

Note: This method is applicable only in python 3.5. When there are conflicting
keys, the interpreter chooses the latest value.


The standard string representation for dictionaries is hard to read. Using the json.dumps we can make the output as JSON with more readability.

      # The standard string representation for dictionary:
      >>> obj = {'a': 'asdasd', 'b':'rgggsd', 'c':'asdsd'}
      >>> obj
          {'a': 'asdasd', 'b':'rgggsd', 'c':'asdsd'}
      >>> import json
      >>> print(json.dumps(obj, indent=4))
             "c": "asdsd",
             "b": 42,
             "a": "asdasd"
Enter fullscreen mode Exit fullscreen mode

json.dumps will accept multiple parameters. As shown above, we can give indent level and we can supply other parameters like sort_keys.

    >>> print(json.dumps(obj, indent=4, sort_keys=True))
       "a": "asdasd",
       "b": "rgggsd",
       "c": "asdsd"
Enter fullscreen mode Exit fullscreen mode


loads() performs the vice-versa of the dumps. It takes the JSON input and converts it back to the dictionary.

      Jobj = {
         "a": "asdasd",
      >>> import json
      >>> print(json.loads(jobj))
      {'a': 'asdasd', 'b':'rgggsd', 'c':'asdsd'}
Enter fullscreen mode Exit fullscreen mode

Dictionary as switch/case statements

Python doesn’t have switch/case statements as default. But as python has
first-class functions, they can be used to emulate switch/case statements.
Following is an example of implementation of switch/case statement using the dictionary.


Python dictionaries very powerful when compared to other data types like lists,
tuples and sets. In other languages, these are also called as “associative
memories” or “associative arrays”. There are lot more properties and methods for
dictionaries which are used as per requirement.


Top comments (0)