How to Iterate Through a Dictionary in Pythonby Leodanis Pozo Ramos intermediate python Mark as Completed Tweet Share Email Table of Contents Remove adsWatch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Dictionary Iteration: Advanced Tips & Tricks Dictionaries are one of the most important and useful data structures in Python. They can help you solve a wide variety of programming problems. This tutorial will take you on a deep dive into how to iterate through a dictionary in Python. By the end of this tutorial, you’ll know:
For more information on dictionaries, you can check out the following resources:
Ready? Let’s go! Free Download: Get a sample chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code. Take the Quiz: Test your knowledge with our interactive “Python Dictionary Iteration” quiz. Upon completion you will receive a score so you can track your learning progress over time: Take the Quiz » Iterate through list of dictionaries in Python
In this article, we will learn how to iterate through a list of dictionaries. List of dictionaries in use:
Iterate over a dictionary with list values using nested for loopFirst, we will iterate over all the items (key-value pairs) of dictionary by applying a for loop over the sequence returned by items() function. As value field of a key-value pair can be a list, so we will check the type of value for each pair. If value is list then iterate over all its items using an another for loop and print it, otherwise just print the value. For example, Advertisements # Create a dictionary where multiple values are # associated with a key word_freq = {'is': [1, 3, 4, 8, 10], 'at': [3, 10, 15, 7, 9], 'test': 33, 'this': [2, 3, 5, 6, 11], 'why': [10, 3, 9, 8, 12]} # Iterate over a dictionary with list values using nested for loop for key, values in word_freq.items(): print('Key :: ', key) if(isinstance(values, list)): for value in values: print(value) else: print(value)Output: Key :: is 1 3 4 8 10 Key :: at 3 10 15 7 9 Key :: test 9 Key :: this 2 3 5 6 11 Key :: why 10 3 9 8 12We iterated over all the key value pairs of dictionary and if any value field from the pair is a list object, then we printed each item of that list too. In our case, except one key, all other keys had the list values. Therefore, for each pair, we first checked if the type of value is list or not. If it is list, then only iterated over all the values from list, otherwise printed the value only. How to Iterate Through List of Dictionaries in PythonThere are multiple ways to iterate through list of dictionaries in python. Basically, you need to use a loop inside another loop. The outer loop, iterates through each dictionary, while the inner loop iterates through the individual elements of each dictionary. There are different ways to do this. You can simply iterate over the range of length of list. dlist = [{'a': 1}, {'b': 3}, {'c': 5}] for index in range(len(dList)): for key in dList[index]: print(dList[index][key])In the outer loop, we use range and length function to create a list that we can iterate through. We use the index value to get each dictionary. In the inner loop, we use key variable to iterate through the current dictionary. Alternatively, you can lop using while loop with an index. dList = [{'a': 1}, {'b': 3}, {'c': 5}] index = 0 while index < len(dList): for key in dList[index]: print(dList[index][key]) index += 1In the above code, we modify the outer loop to use while condition instead of for statement. We use len function to get the length of list of dictionaries and use the index counter to increment from 0 as long as it is less than the length of dictionary list. You can also directly loop through the dictionary elements. dList = [{'a': 1}, {'b': 3}, {'c': 5}] for dic in dList: for key in dic: print(dic[key])You can even use a shortcut that directly loops through the dict, without using len or range functions, in the outer loop. In the inner loop too, there is no need for any lookup. If you don’t want to do any lookups, you can use the following method. dList = [{'a': 1}, {'b': 3}, {'c': 5}] for dic in dList: for val in dic.values(): print(val)Finally, you can also use list comprehensions as shown below to loop through list of dictionaries. dList = [{'a': 1}, {'b': 3}, {'c': 5}] print(*[val for dic in dList for val in dic.values()], sep='\n')In this article, we have looked at different ways to loop through list of dictionaries in Python. You can use any of them as per your requirement. Also read: How to Setup vnstat in Linux Related posts:How to Measure Time Taken By Python Program to Execute How to Send HTML Mail with Attachment Using Python How to Group by Multiple Columns in Python Pandas How to Flatten List of Lists in Python How to Randomly Select Item from List in Python How to Split Python List into N Sublists How to Search Item in List of Dictionaries in Python How to Read YAML File to Dict in Python Using Keys() MethodYou can use the keys() method provided by the dictionary to iterate through the keys of the dictionary. It returns an iterable of the keys available in the dictionary. Then using for loop, you can iterate through the keys as shown below. Snippet for key in mydict.keys(): print(key)Output one two three fourSnippet 2 If you want to access the value of the key, then you can use the get() method to get the value of the specific key during each iteration as shown below. for key in mydict.keys(): print(mydict.get(key))Output 1 2 3 4This is how you can iterate through the dictionary keys using for loop and the keys() method provided by the python dictionaries. Using Values() MethodYou can use the values() method provided by the dictionary to iterate through the values of the dictionary items. It returns an iterable of the values of each item available in the dictionary. Then using for loop, you can iterate through the values as shown below. Snippet for value in mydict.values(): print(value)You’ll see the value of each item in the dictionary printed as below. Output Using this method will not give access to the dictionary keys() which is not necessary in most cases. This makes this method the fastest method to iterate through the dictionary. This is how you can iterate through the dictionary values using for loop and the values() method provided by the python dictionaries. Using Items() methodYou can iterate through the dictionary items using the items() method provided by the python dictionary. items() method returns a tuple of key-value pair during each iteration. Then using for loop, you can iterate through the key-value pair and access both the keys and values in the same iteration as shown below. Snippet for key, value in mydict.items(): print(key ,value)You’ll see the below output. Keys and values will be printed for each iteration and no additional access to the dictionary is necessary to fetch the value of the key. Output one 1 two 2 three 3 four 4This is how you can access the items of the dictionary using for loop and the items() method provided by the dictionaries. Examples Iterate list of dictionaries in PythonSimple example code. Iterate over the indices of the range of the len of the list:Using range() and len() funcitons. lst = [{'a': 1}, {'b': 3}, {'c': 5}] for i in range(len(lst)): for key in lst[i]: print(lst[i][key])Output: Using while loop with an index counter:lst = [{'a': 1}, {'b': 3}, {'c': 5}] index = 0 while index < len(lst): for key in lst[index]: print(lst[index][key]) index += 1Output: 1 Iterate over the elements in the list directlylst = [{'a': 1}, {'b': 3}, {'c': 5}] for dic in lst: for key in dic: print(dic[key])Output: 1 List ComprehensionIterations inside a list-comprehension or a generator and unpack them later: lst = [{'a': 1}, {'b': 3}, {'c': 5}] res = [val for dic in lst for val in dic.values()] print(res)Output: [1, 3, 5] Source: stackoverflow.com Do comment if you have any doubts and suggestions on this Python List dictionary topic.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical. Share this:
RelatedPython Loop Through a Dictionary❮ Python Glossary Loop Through a DictionaryYou can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
ExamplePrint all key names in the dictionary, one by one:
for x in thisdict:
ExamplePrint all values in the dictionary, one by one:
for x in thisdict:
ExampleYou can also use the values() function to return values of a dictionary:
for x in thisdict.values():
ExampleLoop through both keys and values, by using the items() function:
for x, y in thisdict.items(): |