Show
…and other answers to the most popular Stack Overflow questions on Python dictionaries.Photo by Ana M. from PexelsMany of you contacted me asking for valuable resources to nail Python-based Data Engineering interviews. Below I share 3 on-demand courses that I strongly recommend:
Hope you’ll find them useful too! Now enjoy the article :D IntroductionA Python dictionary is defined as a collection of data values, in which items are held as key-value pairs. For this reason, dictionaries are also known as associative arrays. If you are relatively new to Python, or you are preparing for your next coding round, you might have stumbled upon a number of algorithms that require to interact with dictionaries. However, it seems that dictionaries keep generating interest not only among newbies, but also among more experienced developers. In effect, looking at the top Stack Overflow Python questions of all times, it seems that three of the most voted topics are:
In this article, I will attempt to provide you with a succinct and clear answer to each one of this questions. This will spare you from going through dozens of comments on the web. Let’s start from the top! 👆👆🏽👆🏻 How to iterate over dictionaries using a ‘for’ loop?To answer this question, I have created a dictionary including data of a mock online banking transaction: transaction_data = { Method 1: Iteration Using For Loop + IndexingThe easiest way to iterate through a dictionary in Python, is to put it directly in a Then, to also get access to the values, you can pass each key to the dictionary using the indexing operator # METHOD 1 - Unsorted As you can see, the keys are not ordered
alphabetically. To achieve that, you should simply pass # METHOD 1 - Sorted Method 2: Iteration Using .keys( ) + IndexingThe same result can be obtained using the This is particularly handy when you just need to iterate over the keys of a dictionary, but it can also be used in combination with the indexing operator to retrieve values: # METHOD 2 Method 3: Iteration Using .items( )However, the most “pythonic” and elegant way to iterate through a dictionary is by using the print(transaction_data.items())Output[4]: In order to iterate over the keys and the values of the # METHOD 3 Note that k and v are just standard aliases for ‘key’ and ‘value’, but you can opt for an alternative naming convention too. For example using a and b leads to the same output: for a,b in transaction_data.items(): Extra - Iterating Through Nested Dictionaries 🤓But what if you need to iterate through a nested dictionary like transaction_data_n = { In order to unpack the key-value pairs belonging to each nested dictionary, you can use the following loop: #1. Selecting key-value pairs for all the transactionsfor k, v in transaction_data_n.items(): How to check if a given key already exists in a dictionary?You can check membership in Python dictionaries using the In particular, let’s say that you wanted to check whether the ‘send_currency’ in transaction_data.keys()Output[9]: Likewise, to check if the value
‘GBP’ in transaction_data.values()Output[10]: However, the check above won’t immediately tell you if (‘send_currency’, ‘GBP’) in transaction_data.items()Output[10]: If the Handy! 😏😏😏 How to add a new keys to a dictionary?Lastly, let’s pretend that, at some point, the Analytics Team asked you to add both the There are two main method:
transaction_data['user_address'] = '221b Baker Street, London - UK'for k,v in transaction_data.items():
transaction_data.update(user_email=’’)for k,v in transaction_data.items(): ConclusionIn this article, I shared 3 methods to iterate through Python dictionaries with ‘for’ loops and extract key-value pairs efficiently. However, be aware that even more ‘pythonic’ solutions exist ( i.e. dictionary comprehensions). Despite being a relatively basic topic, “how to iterate over Python dictionaries?”, is one of the most voted questions ever asked on Stack Overflow. For this reason, I also answered to other two extremely popular Stack Overflow questions about checking membership and adding new key-value pairs to Python dictionaries. My hope is that you will use this article to clarify all your doubts about dictionaries in the same place. Learning code is fun and will change your life for good, so keep learning! A Note For My ReadersThis post includes affiliate links for which I may make a small commission at no extra cost to you, should you make a purchase. |