avatarIndhumathy Chelliah

Summary

The provided web content offers a comprehensive guide to Python dictionaries, detailing their creation, methods, and operations.

Abstract

The web content titled "An Introduction to Python Dictionary" delves into the intricacies of Python dictionaries, a built-in data type that stores key-value pairs. It explains how dictionaries can be created using braces {} or the dict() constructor, and emphasizes that keys must be unique and immutable, while values can be of any data type. The article covers various methods for creating dictionaries, accessing and updating their values, and iterating over them. It also discusses dictionary methods such as keys(), values(), and items(), which return view objects that reflect changes to the dictionary. The content further elaborates on how to add or remove items, merge dictionaries using update(), and the differences between copy() and deepcopy(). Additionally, it touches on looping techniques, membership tests, and built-in functions like len(), list(), sorted(), reversed(), any(), and all(). The conclusion summarizes the return types of various dictionary operations, and the author provides links to their other blogs on Python data structures and official Python documentation for further reading.

Opinions

  • The author, Indhumathy Chelliah, conveys the importance of understanding Python dictionaries as a fundamental aspect of Python programming.
  • The use of keyword arguments and iterables in creating dictionaries is presented as a flexible approach to initializing dictionaries with predefined data.
  • The article suggests that the get() method is a safer way to access dictionary values compared to direct indexing, as it avoids KeyError by returning None or a specified default value when a key is not found.
  • The author emphasizes the dynamic nature of dictionary view objects, which provide a real-time look at the dictionary's entries.
  • The distinction between copy() and deepcopy() is highlighted to ensure programmers are aware of the potential pitfalls when working with dictionaries containing mutable objects.
  • The author's inclusion of code examples and references to the Python documentation indicates a commitment to providing both practical and authoritative information.
  • The conclusion serves as a quick reference guide, which may be seen as a valuable tool for readers to recall the various functionalities and return types associated with dictionary operations.

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)

2. Creating a dictionary using mapping:

dict(mapping,**kwarg)

3.Creating dictionary using iterable.

dict(iterable,**kwarg)

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.

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.

Using indexing

d[key]

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

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.

  • iter()

iter(d)

Return an iterator over the keys in the dictionary.

  • 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)

  • 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)

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.

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. — python docs

  • 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)

  • 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.

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.

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.-python docs

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

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.-python docs

Looping through the dictionary

Dictionary Operations

Membership Test in, not in

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

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.

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

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

Resources

Python
Python3
Artificial Intelligence
Women In Tech
Technology
Recommended from ReadMedium