Table of contents

Dict

The pre-defined functions (methods) allow manipulation, querying, and management of dictionary objects. Below is a detailed explanation of each method, including the nine listed in the announcement and the two additional standard methods (setdefault() and fromkeys()).

Creates a new dictionary with the specified keys, all assigned the same value (default is None).

Syntax: new_dict = dict.fromkeys(keys, value=None)

Key Notes:

  • The static method is called on the dict class, not an instance.
  • Useful for initializing dictionaries with default values.
keys = ["TS", "KAR", "MH"] d = dict.fromkeys(keys, "Unknown") print(d) # {'TS': 'Unknown', 'KAR': 'Unknown', 'MH': 'Unknown'} d = dict.fromkeys(keys) print(d) # {'TS': None, 'KAR': None, 'MH': None}

Returns the value for the specified key. If the key does not exist, it returns None or a specified default value.

Syntax: value = dictobj.get(key, default=None).

Key Notes:

  • Safer than direct key access (d[key]) as it avoids KeyError.
  • Commonly used for accessing values with fallback options.
d = {"TS": "HYD", "KAR": "BANG", "TAMIL": "CHE", "MH": "MUM"} print(d.get("TS")) # HYD print(d.get("TAMIL")) # CHE print(d.get("GOA")) # None print(d.get("GOA", "Not Found")) # Not Found # print(d["GOA"]) # KeyError: 'GOA'

Returns a view object of the dictionary’s keys.

Syntax: keys = dictobj.keys()

Key Notes:

  • The view object is dynamic, reflecting changes to the dictionary.
  • Useful for iterating over keys.
d = {"TS": "HYD", "KAR": "BANG", "TAMIL": "CHE", "MH": "MUM"} states = d.keys() print(states) # dict_keys(['TS', 'KAR', 'TAMIL', 'MH']) for state in d.keys(): print(state) # TS, KAR, TAMIL, MH

Returns a view object of the dictionary’s values.

Syntax: values = dictobj.values().

Key Notes:

  • Like keys(), the view object is dynamic.
  • Useful for accessing all values without keys.
d = {"TS": "HYD", "KAR": "BANG", "TAMIL": "CHE", "MH": "MUM"} capitals = d.values() print(capitals) # dict_values(['HYD', 'BANG', 'CHE', 'MUM']) for cap in d.values(): print(cap) # HYD, BANG, CHE, MUM

Returns a view object of the dictionary’s key-value pairs as tuples.

Syntax: items = dictobj.items().

Key Notes:

  • Useful for iterating over both keys and values simultaneously.
  • The view object is dynamic, reflecting dictionary changes.
d = {"TS": "HYD", "KAR": "BANG", "TAMIL": "CHE", "MH": "MUM"} keysvals = d.items() print(keysvals) # dict_items([('TS', 'HYD'), ('KAR', 'BANG'), ('TAMIL', 'CHE'), ('MH', 'MUM')]) for state, cap in d.items(): print(state, "===>", cap) # TS ===> HYD, KAR ===> BANG, TAMIL ===> CHE, MH ===> MUM

Updates the dictionary with key-value pairs from another dictionary or iterable, overwriting existing keys.

Syntax: dictobj.update(other).

Key Notes:

  • Modifies the dictionary in place.
  • Can accept another dictionary or an iterable of key-value pairs (e.g., list of tuples).
d1 = {10: 3.4, 20: 4.5, 30: 6.7, 40: 3.4} d2 = {100: 1.2, 200: 2.2} d1.update(d2) print(d1) # {10: 3.4, 20: 4.5, 30: 6.7, 40: 3.4, 100: 1.2, 200: 2.2} d3 = {10: 12.3, 200: 13.4} d1.update(d3) print(d1) # {10: 12.3, 20: 4.5, 30: 6.7, 40: 3.4, 100: 1.2, 200: 13.4}

Returns the value for the specified key. If the key does not exist, it inserts the key with the default value (or None) and returns it.

Syntax: value = dictobj.setdefault(key, default=None)

Key Notes:

  • Combines get() and key insertion in one operation.
  • Useful for initializing missing keys (e.g., in counting scenarios).
d = {10: "Python", 20: "Django"} print(d.setdefault(20, "Flask")) # Django (key exists) print(d.setdefault(30, "Data Sci")) # Data Sci (key added) print(d) # {10: 'Python', 20: 'Django', 30: 'Data Sci'} print(d.setdefault(40)) # None (key added with None) print(d) # {10: 'Python', 20: 'Django', 30: 'Data Sci', 40: None}

Removes all key-value pairs from the dictionary, leaving it empty.

Syntax: dictobj.clear().

Key Notes:

  • Modifies the dictionary in place (same memory address).
  • The dictionary becomes {} but retains its identity.
d1 = {10: "Python", 20: "Django", 30: "Data Sci", 40: "ML", 50: "DL"} print(d1, id(d1)) # {10: 'Python', 20: 'Django', 30: 'Data Sci', 40: 'ML', 50: 'DL'} <id> print(len(d1)) # 5 d1.clear() print(d1, id(d1)) # {} <same id> print(len(d1)) # 0

Creates a shallow copy of the dictionary, allowing modifications to the copy without affecting the original.

Syntax: dictobj2 = dictobj1.copy().

Key Notes:

  • Returns a new dictionary with a different memory address.
  • Shallow copy means nested objects (e.g., lists as values) are not deeply copied.
d1 = {10: "Python", 20: "Django", 30: "Data Sci", 40: "ML", 50: "DL"} print(d1, id(d1)) # {10: 'Python', 20: 'Django', 30: 'Data Sci', 40: 'ML', 50: 'DL'} <id1> d2 = d1.copy() print(d2, id(d2)) # {10: 'Python', 20: 'Django', 30: 'Data Sci', 40: 'ML', 50: 'DL'} <id2> d2[40] = "Tensor-Flow" print(d2, id(d2)) # {10: 'Python', 20: 'Django', 30: 'Data Sci', 40: 'Tensor-Flow', 50: 'DL'} <id2> print(d1, id(d1)) # {10: 'Python', 20: 'Django', 30: 'Data Sci', 40: 'ML', 50: 'DL'} <id1>

Removes and returns the value associated with the specified key. Raises KeyError if the key does not exist.

Syntax: value = dictobj.pop(key).

Key Notes:

  • Modifies the dictionary by removing the specified key-value pair.
  • Useful for extracting and deleting a specific entry.
d1 = {10: "Python", 20: "Django", 30: "Data Sci", 40: "ML", 50: "DL"} print(d1) # {10: 'Python', 20: 'Django', 30: 'Data Sci', 40: 'ML', 50: 'DL'} print(d1.pop(20)) # Django print(d1) # {10: 'Python', 30: 'Data Sci', 40: 'ML', 50: 'DL'} print(d1.pop(30)) # Data Sci print(d1) # {10: 'Python', 40: 'ML', 50: 'DL'} # d1.pop(400) # KeyError: 400

Removes and returns the last inserted key-value pair as a tuple. Raises KeyError if the dictionary is empty.

Syntax: key_value = dictobj.popitem().

Key Notes:

  • Since Python 3.7+, dictionaries maintain insertion order, so popitem() removes the last added pair.
  • Useful for stack-like operations.
d1 = {10: "Python", 20: "Django", 30: "Data Sci", 40: "ML", 50: "DL"} print(d1) # {10: 'Python', 20: 'Django', 30: 'Data Sci', 40: 'ML', 50: 'DL'} print(d1.popitem()) # (50, 'DL') print(d1) # {10: 'Python', 20: 'Django', 30: 'Data Sci', 40: 'ML'} print(d1.popitem()) # (40, 'ML') print(d1) # {10: 'Python', 20: 'Django', 30: 'Data Sci'} # d1.popitem() on {} # KeyError: 'popitem(): dictionary is empty'

The del statement is a Python keyword used to remove objects or specific components of objects, such as dictionary key-value pairs, list elements, or entire variables. In the context of dictionaries, del is commonly used to delete a specific key-value pair or the entire dictionary.

# Delete a specific key-value pair: del dictobj[key]
  • Removes the key-value pair associated with key.
  • Raises KeyError if key does not exist.
# delete entire dict del dictobj
  • Removes the dictionary object entirely, making it inaccessible.
  • Subsequent access raises NameError.