Python Dictionaries and their operations
Tags: pythondictionaries
Published: 2019-07-07 15:55:40


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.

{% gist https://gist.github.com/suryasr007/8e8633831729a3ec765dafa399a48d7b %}

### Loops on Dictionaries

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

* dict.items()
* dict.keys()
* dict.values()

{% gist https://gist.github.com/suryasr007/a0bb6e9056e8714e7ab3c59def388979 %}

### 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.
``` python
    >>> Boys = {'sunny': 26,'Chary':18,'Robin':25}
    >>> Girls = {'pari':22} 
    >>> print(cmp(Girls, Boys))
    -1
```
**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.
```python
    # dict.get( key, default )
    >>> Boys.get('sunny')
    26
    >>> Boys.get('surya', 'Not Found')
    'Not Found'
    >>> Boys.get('surya')
    None
```
**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.
``` python
      >>> x = {'a': 1, 'b': 2}
      >>> y = {'b': 3, 'c': 4}
      >>> z = {**x, **y}
          {'a': 1, 'b': 3, 'c': 4}
```
*Note*: This method is applicable only in python 3.5. When there are conflicting
keys, the interpreter chooses the latest value.

**json.dumps()**

The standard string representation for dictionaries is hard to read. Using the json.dumps we can make the output as JSON with more readability.
``` python
      # 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"
          }
```
json.dumps will accept multiple parameters. As shown above, we can give indent level and we can supply other parameters like sort_keys.
``` python
    >>> print(json.dumps(obj, indent=4, sort_keys=True))
    {    
       "a": "asdasd",
       "b": "rgggsd",
       "c": "asdsd"
    }
```
**json.loads()**

`loads()` performs the vice-versa of the dumps. It takes the JSON input and converts it back to the dictionary.
```python
      Jobj = {
         "a": "asdasd",
         "b":"rgggsd",
         "c":"asdsd"
      }
      >>> import json
      >>> print(json.loads(jobj))
      {'a': 'asdasd', 'b':'rgggsd', 'c':'asdsd'}
```
**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.
{% gist https://gist.github.com/suryasr007/c0fa8d13e89bfbd374920102c1e2ca84 %}

### Conclusion:

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.

**Sources:**

* [Python](https://medium.com/tag/python?source=post)
* [Dictionary](https://medium.com/tag/dictionary?source=post)