DEV Community

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

Posted on

1 1

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.

# Defining a dictionary
>>> tel = {'jack': 4098, 'sape': 4139}
# If dict keys are only string, we can define as below
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}
# Appending a new key value pair to the `tel` dict
>>> tel['guido'] = 4127
# Display items in dictionary
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
# Delete a item from `tel` dict
>>> del tel['sape']
# Represent all the keys of the `tel` in a list
>>> list(tel.keys())
['irv', 'guido', 'jack']
# sort the keys
>>> sorted(tel.keys())
['guido', 'irv', 'jack']
# Check whether a key exists in the `tel` dict
>>> 'guido' in tel
True
>>> 'jack' not in tel
False

Loops on Dictionaries

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

  • dict.items()
  • dict.keys()
  • dict.values()
# Looping can be done using dict.keys(), dict.values() and dict.items()
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
# Using items(), we can retrieve key as well as value for each item
>>> for k, v in knights.items():
print(k, v)
gallahad the pure
robin the brave
# To loop through only keys()
>>> for k in knights.keys():
print(k)
gallahad
robin
# To through loop only values
>>> for k in knights.values():
print(k)
the pure
the brave
view raw dict_looping.py hosted with ❤ by GitHub

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))
    -1
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')
    26
    >>> Boys.get('surya', 'Not Found')
    'Not Found'
    >>> Boys.get('surya')
    None
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.

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.

      # 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

json.loads()

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

      Jobj = {
         "a": "asdasd",
         "b":"rgggsd",
         "c":"asdsd"
      }
      >>> 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.

def operations(operator, x, y):
return {
'add': lambda: x + y,
'sub': lambda: x - y,
'mul': lambda: x * y,
'div': lambda: x / y,
}.get(operator, lambda: None)()
>>> operations('mul', 2, 8)
16
view raw dict_switch.py hosted with ❤ by GitHub

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:

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay