3 Ways To Iterate Over Python Dictionaries Using For Loops | by AnBento | Towards Data Science

Many 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:
Python Data Engineering Nanodegree→ High Quality Course + Coding Projects If You Have Time To Commit. **Up to 25% DISCOUNT USING THIS CODE!**
LeetCode In Python: 50 Algorithms Coding Interview Questions → Best For Coding Rounds Involving Algorithms!
Python advanced Coding Problems (StrataScratch)→ Best platform I found to prepare Python & SQL coding interviews so far! Better and cheaper than LeetCode.
Hope you’ll find them useful too! Now enjoy the article :D
A 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:
How to iterate over dictionaries using a ‘for’ loop?
How to check if a given key already exists in a dictionary?
How to add a new keys to a dictionary?
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! 👆👆🏽👆🏻
To answer this question, I have created a dictionary including data of a mock online banking transaction:
transaction_data = { ‘transaction_id’: 1000001, ‘source_country’: ‘United Kingdom’, ‘target_country’: ‘Italy’, ‘send_currency’: ‘GBP’, ‘send_amount’: 1000.00, ‘target_currency’: ‘EUR’, ‘fx_rate’: 1.1648674, ‘fee_pct’: 0.50,  ‘platform’: ‘mobile’}
The easiest way to iterate through a dictionary in Python, is to put it directly in a for loop. Python will automatically treat transaction_data as a dictionary and allow you to iterate over its keys.
Then, to also get access to the values, you can pass each key to the dictionary using the indexing operator[]:
# METHOD 1 - Unsortedfor key in transaction_data:   print(key, ‘:’, transaction_data[key])Output[1]:transaction_id : 1000001source_country : United Kingdomtarget_country : Italysend_currency : GBPsend_amount : 1000.0target_currency : EURfx_rate : 1.1648674fee_pct : 0.5platform : mobile
As you can see, the keys are not ordered alphabetically. To achieve that, you should simply pass transaction_data to the sorted() method:
# METHOD 1 - Sortedfor key in sorted(transaction_data):   print(key, ‘:’, transaction_data[key])Output[2]:fee_pct : 0.5fx_rate : 1.1648674platform : mobilesend_amount : 1000.0send_currency : GBPsource_country : United Kingdomtarget_country : Italytarget_currency : EURtransaction_id : 1000001
The same result can be obtained using the .keys() method that returns a Python object including the dictionary’s keys.
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 2for key in transaction_data.keys():    print(key, '-->', transaction_data[key])Output[3]:transaction_id --> 1000001source_country --> United Kingdomtarget_country --> Italysend_currency --> GBPsend_amount --> 1000.0target_currency --> EURfx_rate --> 1.1648674fee_pct --> 0.5platform --> mobile
However, the most “pythonic” and elegant way to iterate through a dictionary is by using the .items() method, that returns a view of dictionary’s items as tuples:
print(transaction_data.items())Output[4]:dict_items([('transaction_id', 1000001),             ('source_country', 'United Kingdom'),             ('target_country', 'Italy'),             ('send_currency', 'GBP'),             ('send_amount', 1000.0),             ('target_currency', 'EUR'),             ('fx_rate', 1.1648674),             ('fee_pct', 0.5),             ('platform', 'mobile')])
In order to iterate over the keys and the values of the transaction_data dictionary, you just need to ‘unpack’ the two items embedded in the tuple as shown below:
# METHOD 3for k,v in transaction_data.items():    print(k,’>>’,v)Output[5]:transaction_id >> 1000001source_country >> United Kingdomtarget_country >> Italysend_currency >> GBPsend_amount >> 1000.0target_currency >> EURfx_rate >> 1.1648674fee_pct >> 0.5platform >> mobile
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():    print(a,’~’,b)Output[6]:transaction_id ~ 1000001source_country ~ United Kingdomtarget_country ~ Italysend_currency ~ GBPsend_amount ~ 1000.0target_currency ~ EURfx_rate ~ 1.1648674fee_pct ~ 0.5platform ~ mobile
But what if you need to iterate through a nested dictionary like transaction_data_n ? Well, in this case, each one of the keys represents a transaction and has a dictionary as a value:
transaction_data_n = { ‘transaction_1’:{ ‘transaction_id’: 1000001, ‘source_country’: ‘United Kingdom’, ‘target_country’: ‘Italy’, ‘send_currency’: ‘GBP’, ‘send_amount’: 1000.00, ‘target_currency’: ‘EUR’, ‘fx_rate’: 1.1648674, ‘fee_pct’: 0.50,  ‘platform’: ‘mobile’ }, ‘transaction_2’:{ ‘transaction_id’: 1000002, ‘source_country’: ‘United Kingdom’, ‘target_country’: ‘Germany’, ‘send_currency’: ‘GBP’, ‘send_amount’: 3320.00, ‘target_currency’: ‘EUR’, ‘fx_rate’: 1.1648674, ‘fee_pct’: 0.50,  ‘platform’: ‘Web’ }, ‘transaction_3’:{ ‘transaction_id’: 1000003, ‘source_country’: ‘United Kingdom’, ‘target_country’: ‘Belgium’, ‘send_currency’: ‘GBP’, ‘send_amount’: 1250.00, ‘target_currency’: ‘EUR’, ‘fx_rate’: 1.1648674, ‘fee_pct’: 0.50,  ‘platform’: ‘Web’ }}
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():    if type(v) is dict:        for nk, nv in v.items():             print(nk,’ →’, nv)#nk and nv stand for nested key and nested valueOutput[7]:transaction_id --> 1000001source_country --> United Kingdomtarget_country --> Italysend_currency --> GBPsend_amount --> 1000.0target_currency --> EURfx_rate --> 1.1648674fee_pct --> 0.5platform --> mobiletransaction_id --> 1000002source_country --> United Kingdomtarget_country --> Germanysend_currency --> GBPsend_amount --> 3320.0target_currency --> EURfx_rate --> 1.1648674fee_pct --> 0.5platform --> Webtransaction_id --> 1000003source_country --> United Kingdomtarget_country --> Belgiumsend_currency --> GBPsend_amount --> 1250.0target_currency --> EURfx_rate --> 1.1648674fee_pct --> 0.5platform --> Web-----------------------------#2. Selecting key-value pairs for 'transaction_2 only'for k, v in transaction_data_n.items():    if type(v) is dict and k == 'transaction_2':        for sk, sv in v.items():            print(sk,'-->', sv)Output[8]:transaction_id --> 1000002source_country --> United Kingdomtarget_country --> Germanysend_currency --> GBPsend_amount --> 3320.0target_currency --> EURfx_rate --> 1.1648674fee_pct --> 0.5platform --> Web
You can check membership in Python dictionaries using the in operator.
In particular, let’s say that you wanted to check whether the send_currency field was available as a key in transaction_data. In this case you could run:
‘send_currency’ in transaction_data.keys()Output[9]:True
Likewise, to check if the value GBP was already assigned to a key in the dictionary, you could run:
‘GBP’ in transaction_data.values()Output[10]:True
However, the check above won’t immediately tell you if GBP is the value assigned to the send_currency key or the target_currency key. In order to confirm that, you can pass a tuple to the values() method:
(‘send_currency’, ‘GBP’) in transaction_data.items()Output[10]:True('target_currency', 'GBP') in transaction_data.items()Output[11]:False
If the transaction_data dictionary included hundreds of values, this would be the perfect way to check that GBP is indeed the send_currency for that specific transaction.
Handy! 😏😏😏
Lastly, let’s pretend that, at some point, the Analytics Team asked you to add both the user_address and the user_email fields to the the data available in the dictionary. How would you achieve that?
There are two main method:
Using the square brackets [] notation:
transaction_data['user_address'] = '221b Baker Street, London - UK'for k,v in transaction_data.items():    print(k,’:’,v)Output[12]:transaction_id : 1000001source_country : United Kingdomtarget_country : Italysend_currency : GBPsend_amount : 1000.0target_currency : EURfx_rate : 1.1648674fee_pct : 0.5platform : mobileuser_address : 221b Baker Street, London - UK
Alternatively, you could use the update() method, but there is a bit more typing involved:
transaction_data.update(user_email=’user@example.com’)for k,v in transaction_data.items():    print(k,’::’,v)Output[13]:transaction_id :: 1000001source_country :: United Kingdomtarget_country :: Italysend_currency :: GBPsend_amount :: 1000.0target_currency :: EURfx_rate :: 1.1648674fee_pct :: 0.5platform :: mobileuser_address :: 221b Baker Street, London - UKuser_email :: user@example.com
In 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!
This post includes affiliate links for which I may make a small commission at no extra cost to you, should you make a purchase.