How to loop a dictionary in Python

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'])

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.

Nguyen Vu Ngoc Tung

I love making new professional acquaintances. Don't hesitate to contact me via nguyenvungoctung@gmail.com if you want to talk about information technology, education, and research on complex networks analysis (i.e., metabolic networks analysis), data analysis, and applications of graph theory. Specialties: researching and proposing innovative business approaches to organizations, evaluating and consulting about usability engineering, training and employee development, web technologies, software architecture.

https://www.itersdesktop.com/author/nvntung/

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.