How To Create A Dictionary In Python Using Loop
3 Ways To Iterate Over Python Dictionaries Using For Loops
…and other answers to the most popular Stack Overflow questions on Python dictionaries.
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 75% DISCOUNT IN SEPT 2021**
- 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
Introduction
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.
Howe v er, 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! πππ½ππ»
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 = {
'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'
}
Method 1: Iteration Using For Loop + Indexing
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 - Unsorted
for key in transaction_data:
print(key, ':', transaction_data[key]) Output[1]:
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
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 - Sorted
for key in sorted(transaction_data):
print(key, ':', transaction_data[key]) Output[2]:
fee_pct : 0.5
fx_rate : 1.1648674
platform : mobile
send_amount : 1000.0
send_currency : GBP
source_country : United Kingdom
target_country : Italy
target_currency : EUR
transaction_id : 1000001
Method 2: Iteration Using .keys( ) + Indexing
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 2
for key in transaction_data.keys():
print(key, '-->', transaction_data[key]) Output[3]:
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
Method 3: Iteration Using .items( )
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 3
for k,v in transaction_data.items():
print(k,'>>',v) Output[5]:
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
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 ~ 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
Extra - Iterating Through Nested Dictionaries π€
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 transactions for 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 value Output[7]:
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
transaction_id --> 1000002
source_country --> United Kingdom
target_country --> Germany
send_currency --> GBP
send_amount --> 3320.0
target_currency --> EUR
fx_rate --> 1.1648674
fee_pct --> 0.5
platform --> Web
transaction_id --> 1000003
source_country --> United Kingdom
target_country --> Belgium
send_currency --> GBP
send_amount --> 1250.0
target_currency --> EUR
fx_rate --> 1.1648674
fee_pct --> 0.5
platform --> 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 --> 1000002
source_country --> United Kingdom
target_country --> Germany
send_currency --> GBP
send_amount --> 3320.0
target_currency --> EUR
fx_rate --> 1.1648674
fee_pct --> 0.5
platform --> Web
How to check if a given key already exists in a dictionary?
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! πππ
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 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 : 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
user_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 :: 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
user_address :: 221b Baker Street, London - UK
user_email :: user@example.com
Conclusion
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!
How To Create A Dictionary In Python Using Loop
Source: https://towardsdatascience.com/3-ways-to-iterate-over-python-dictionaries-using-for-loops-14e789992ce5
Posted by: healeywimen1958.blogspot.com
0 Response to "How To Create A Dictionary In Python Using Loop"
Post a Comment