An Introduction to Python Dictionary

Let’s dive deeper and know about the python dictionary.

Photo by Nil Castellví on Unsplash

Python Dictionary

Dictionaries can be created by placing a comma-separated list of key: value pairs within braces{} or by using dict() constructor. An empty dictionary is represented by {}. The dictionary contains key-value pairs. Keys are unique and can be of any immutable datatype like string, tuples, or numbers. The values of a dictionary can be of any datatype. We can access the items in the dictionary by using a key. Dictionary is unordered.

Topics covered in this story

Image by Author

Different ways of creating a dictionary using dict() constructor

dict(**kwarg)
dict(mapping, **kwarg)
dict(iterable, **kwarg)

**kwarg-arbitary number of keyword arguments

  1. Creating a dictionary from keyword arguments:

dict(**kwarg)

https://gist.github.com/IndhumathyChelliah/7c9968dcef36cb18ee8031ba022f8c2f

2. Creating a dictionary using mapping:

dict(mapping,**kwarg)

https://gist.github.com/IndhumathyChelliah/4a786a285966de04a471910ce50fdad2

3.Creating dictionary using iterable.

dict(iterable,**kwarg)

https://gist.github.com/IndhumathyChelliah/86ca687258ea86abbc8ba9437a003355


Dictionary methods.

  • keys()
    Return a new view of dictionary’s keys.
  • values()
    Return a new view of the dictionary’s values.
  • items()
    Return a new view of dictionary’s items (key,value)pairs.

https://gist.github.com/IndhumathyChelliah/407000f2eb970814ada79cd8f31e954f


Accessing the values from the dictionary

We can access the values by using the get method and also by indexing. If the key doesn’t exist in the dictionary means, get method returns None.
But when we use indexing, it will raise KeyError.

  • get()

get(key,default)

Returns the value of that specified key. If the key doesn’t exist in the dictionary means returns None. If the default is specified, it will return the default value if the key doesn’t exist.

https://gist.github.com/IndhumathyChelliah/1f3720601dabaa0362bf6addd6267129

Using indexing

d[key]

Returns the value of the key. If the key doesn’t exist in the dictionary means it will raise KeyError.

https://gist.github.com/IndhumathyChelliah/36caba3589160c94c0375037b694bea9


Assigning /Updating values

d[key]=value

Set d[key] to value. If the key already exists in the dictionary means, it will update the value. If the key doesn’t exist in the dictionary means, it will add that key, value pair.

https://gist.github.com/IndhumathyChelliah/be083526ce6f011a53bad73731cec8cf

  • iter()

iter(d)

Return an iterator over the keys in the dictionary.

https://gist.github.com/IndhumathyChelliah/f265d7937cb3b79b06ca7a9ce943164e

  • fromkeys()
    Create a new dictionary with keys from iterable and values set to value.
    fromkeys() is a class method that returns a new dictionary. value defaults to None.

fromkeys(iterable,value)

https://gist.github.com/IndhumathyChelliah/ccefe6feb0936b700d389bc48410a5ea

  • setdefault()
    setdefault() method returns the value of a key (if the key is in the dictionary).
    If not, it inserts a key with a value to the dictionary. If the key is only mentioned, it will insert key with value as None.

setdefault(key,default)

https://gist.github.com/IndhumathyChelliah/09a2f64f6f0cb04ce1f43f72805f6a8b


Updating the items in the dictionary

  • update()
    update() method is used to merge the second dictionary into the first dictionary. It will update the value of the first dictionary.
    It won’t create a new dictionary. It is used for merging two dictionaries.
    Update() method adds elements to the dictionary if the key is not in that dictionary. If the key is in the dictionary means, it will update the new value.Update() function won’t return any value.

update(other)

other argument can be another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs.

https://gist.github.com/IndhumathyChelliah/f01bce8158cbdee90d8a43e7a4eeab54


Removing items from the dictionary

  • popitem()
    Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order. If the dictionary is empty, calling popitem() raises a KeyError.
  • pop()
    If the key is in the dictionary, remove it and return its value, else return default. If the default is not given and the key is not in the dictionary, a KeyError is raised.

pop(key,default)

https://gist.github.com/IndhumathyChelliah/32391a665b4bd2736215cad5d9c5e907

  • clear()
    clear() will empty the dictionary.Its return value is None.
    del keyword is used to delete the dictionary itself.
    We can also delete the key from the dictionary by using del keyword. If the key is not in the dictionary means, then it will raise KeyError.

https://gist.github.com/IndhumathyChelliah/f742ebf86aa63622b74c27d20ca98ca5


copy() vs deepcopy()

copy() method returns the shallow copy of the existing dictionary. A shallow copy means a new dictionary value is updated with references to objects in the existing dictionary.
If we change the value of immutable data types in the original dictionary means, it is not reflected in the copied dictionary. But if we change the value of mutable datatypes like list means changes are reflected in the copied dictionary also.
To avoid this, we can use a deep copy(). In deepcopy(), if we change either mutable or immutable data types of the original dictionary, changes are not reflected in a deep copied dictionary.

https://gist.github.com/IndhumathyChelliah/5d7f123c592c7daaa275e3f67dd801a7


Dictionary view objects

The objects returned by dict.keys(), dict.values() and dict.items() are view objects. They provide a dynamic view of the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.

Dictionary views can be iterated over to yield their respective data and support membership tests.

iter(dictview)

Return an iterator over the keys, values, or items in the dictionary

https://gist.github.com/IndhumathyChelliah/07cda1bfad55c6394af184173e95d664

reversed(dictview)

Return a reverse iterator over the keys, values, or items of the dictionary. The view will be iterated in reverse order of the insertion.

https://gist.github.com/IndhumathyChelliah/14875fdddcb1019d5bcb245ee4b48246


Looping through the dictionary

https://gist.github.com/IndhumathyChelliah/ba62feb145fc6b6ae6593c4d6354ce1b


Dictionary Operations

Membership Test
in, not in

in — Returns True if the key is present in the dictionary. Checks only key and not values.

https://gist.github.com/IndhumathyChelliah/1634d9cd272ec8be632b2266e0cebd58


Dictionary built-in functions

  1. len() — Returns the length (no of items) of the dictionary.
  2. list()-Returns the list of all keys in the dictionary
  3. sorted()-Returns the sorted list of keys in the dictionary.
  4. reversed()-Return a reversed iterator over the keys of the dictionary.

https://gist.github.com/IndhumathyChelliah/b10a89aa48e3658dcc78b8ba2f4edd32

4. all(): Returns True if all keys(not values) in the dictionary is True or if the dictionary is empty.

5. any():Returns True if any key(not values) in the dictionary is True.If dictionary is empty returns False

https://gist.github.com/IndhumathyChelliah/41b5a6df6f003c1a53734b378e1afdc1


Conclusion

  • Return type is view object
    keys()
    values()
    items()
  • Return type is List
    list(d),sorted(d)
  • Return type is iterator
    iter(d),reversed(d),iter(dictview)
  • Return type is dictionary
    copy(),deepcopy(),fromkeys()
  • Return type is tuple
    popitem()
  • Return type is None
    clear()- Doesn’t return anything.It will clear the original dictionary.
    update()-Doesn’t return anything.It will update the original dictionary.
  • Return type is integer
    len()
  • Return type is Boolean
    any(),all()
  • reversed(d)- supported from Python version 3.8

My other blogs on Python data structures

An Introduction to Python List

An Introduction to Python Set

An Introduction to Python Tuple

String Methods in Python


Resources

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s