Why is iterating over a dictionary slow in Python? Last Updated : 22 Jul, 2021 Comments Improve Suggest changes Like Article Like Report In this article, we are going to discuss why is iterating over a dict so slow in Python? Before coming to any conclusion lets have a look at the performance difference between NumPy arrays and dictionaries in python: Python # import modules import numpy as np import sys # compute numpy performance def np_performance(): array = np.empty(100000000) for i in range(100000000): array[i] = i print("SIZE : ", sys.getsizeof(array)/1024.0**2, "MiB") # compute dictionary performance def dict_performance(): dic = dict() for i in range(100000000): dic[i] = i print("SIZE : ", sys.getsizeof(dic)/1024.0**2, "MiB") In the above Python Script we have two functions : np_performance: This function creates an empty NumPy array for 10,00,000 elements and iterates over the entire array updating individual element's value to the iterator location ('i' in this case)dict_performance: This function creates an empty Dictionary for 10,00,000 elements and iterates over the entire dictionary updating individual element's value to the iterator location ('i' in this case) And finally, a sys.getsizeof() function call to calculate the memory usage by respective data structures. Now we call both these functions, and to measure the time taken by each function we use %time function which gives us the Time execution of a Python statement or expression. %time function can be used both as a line and cell magic: In the inline mode, you can time a single-line statement (though multiple ones can be chained using semicolons).In cell mode, you can time the cell body (a directly following statement raises an error). Calling these functions from inline mode using %time method : Python3 # compute time taken %time np_performance() Output: Python3 # compute time taken %time dict_performance() Output: As we can see there is quite a difference in Wall time between iterating on a NumPy array and a python dictionary. This difference in performance is due to the internal working differences between arrays and dictionaries as after Python 3.6, Dictionaries in python are based on a hybrid of HashTables and an array of elements. So whenever we take out/delete an entry from the dictionary, rather than deleting a key from that particular location, it allows the next key to be replaced by deleted key's position. What python dictionary does is replace the value from the hash array with a dummy value representing null. So upon traversing when you encounter these dummy null values it keeps on iterating till it finds the next real-valued key.Since there may be lots of empty spaces we'll be traversing on without any real benefits and hence Dictionaries are generally slower than their array/list counterparts.For large-sized Datasets, memory access would be the bottleneck. Dictionaries are mutable, and take up more memory than arrays or (named) tuples (when organized efficiently, not duplicating type information). Comment More infoAdvertise with us Next Article Why is iterating over a dictionary slow in Python? devashish_ Follow Improve Article Tags : Python python-dict Practice Tags : pythonpython-dict Similar Reads Ways to change keys in dictionary - Python Given a dictionary, the task is to change the key based on the requirement. Let's see different methods we can do this task in Python. Example:Pythond = {'nikhil': 1, 'manjeet': 10, 'Amit': 15} val = d.pop('Amit') d['Suraj'] = val print(d)Output{'nikhil': 1, 'manjeet': 10, 'Suraj': 15} Explanation:T 2 min read Python Program to Swap dictionary item's position Given a Dictionary, the task is to write a python program to swap positions of dictionary items. The code given below takes two indices and swap values at those indices. Input : test_dict = {'Gfg' : 4, 'is' : 1, 'best' : 8, 'for' : 10, 'geeks' : 9}, i, j = 1, 3 Output : {'Gfg': 4, 'for': 10, 'best': 4 min read Merging or Concatenating two Dictionaries in Python Combining two dictionaries is a common task when working with Python, especially when we need to consolidate data from multiple sources or update existing records. For example, we may have one dictionary containing user information and another with additional details and we'd like to merge them into 2 min read How to Compare Two Dictionaries in Python In this article, we will discuss how to compare two dictionaries in Python. The simplest way to compare two dictionaries for equality is by using the == operator.Using == operatorThis operator checks if both dictionaries have the same keys and values.Pythond1 = {'a': 1, 'b': 2} d2 = {'a': 1, 'b': 2} 2 min read Python Dictionary Comprehension Like List Comprehension, Python allows dictionary comprehensions. We can create dictionaries using simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in iterable}Python Dictionary Comprehension ExampleHere we have two lists named keys and value and we are iter 4 min read How to Add Values to Dictionary in Python The task of adding values to a dictionary in Python involves inserting new key-value pairs or modifying existing ones. A dictionary stores data in key-value pairs, where each key must be unique. Adding values allows us to expand or update the dictionary's contents, enabling dynamic manipulation of d 3 min read Add new keys to a dictionary in Python In this article, we will explore various methods to add new keys to a dictionary in Python. Let's explore them with examples:Using Assignment Operator (=)The simplest way to add a new key is by using assignment operator (=).Pythond = {"a": 1, "b": 2} d["c"] = 3 print(d)Output{'a': 1, 'b': 2, 'c': 3} 2 min read Add Item after Given Key in Dictionary - Python The task of adding an item after a specific key in a Pythondictionary involves modifying the order of the dictionary's key-value pairs. Since Python dictionaries maintain the insertion order, we can achieve this by carefully placing the new key-value pair after the target key. For example, consider 4 min read Python - Ways to remove a key from dictionary We are given a dictionary and our task is to remove a specific key from it. For example, if we have the dictionary d = {"a": 1, "b": 2, "c": 3}, then after removing the key "b", the output will be {'a': 1, 'c': 3}.Using pop()pop() method removes a specific key from the dictionary and returns its cor 3 min read Removing Dictionary from List of Dictionaries - Python We are given a list of dictionaries, and our task is to remove specific dictionaries based on a condition. For instance given the list: a = [{'x': 10, 'y': 20}, {'x': 30, 'y': 40}, {'x': 50, 'y': 60}], we might want to remove the dictionary where 'x' equals 30 then the output will be [{'x': 10, 'y': 3 min read Like