Dictionary is one of the most widely used data structures in programming, especially with Python. To understand how to loop on it, extract its keys as well as retrieve all its values are important for any programmer. In this post, I want to share with you how to iterate on a dictionary in a minute.
Presumably, we have a dictionary, called metabolites , declared as below.
dict_items([
('Glucose', ['PTS_Glc']),
('PEP', ['PTS_Glc', 'ENO', 'PYK', 'PTS_Man']),
('G6P', ['PTS_Glc', 'PGI']),
('PYR', ['PTS_Glc', 'PYK', 'LDH', 'PDH', 'PA', 'PTS_Man']),
('ATP', ['ATPase', 'P_transp', 'PFK', 'ENO', 'PYK', 'AC']),
('ADP', ['ATPase', 'P_transp', 'PFK', 'ENO', 'PYK', 'AC']),
('Pint', ['ATPase', 'P_transp', 'GAPDH', 'FBPase']),
('Pext', ['P_transp']),
('F6P', ['PGI', 'PFK', 'MPD', 'FBPase'])
Table of Contents
Standard loop
By default, we can use the typical way to scan all elements of a dictionary by using the following snippet.
for e in metabolites:
print(e)
With the above simple statements, Python will print all dictionary keys, so the output looks like
Glucose PEP G6P PYR ATP ADP Pint Pext
Retrieve keys and values
In reality, we often need to retrieve each key and its values at the same time. To do so, we use metabolites.items() . Below is the way we can do.
ext_met = []
for k, v in metabolites.items():
if len(v) == 1:
ext_met.append(k)

References
The Python Tutorial >> Data Structures >> Dictionaries, retrieved on July 1st, 2019
That’s alright.
