Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a short form for accessing dictionary values in for loop in Python?

Is there a short form for accessing dictionary values in for loop in Python?

I have the following example code:

dict = [{"name": "testdata"}, {"name": "testdata2"}]

for x in dict:
    print(x["name"])

Is there a way to write the dictionary key directly into the line of the for loop, e.g.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

dict = [{"name": "testdata"}, {"name": "testdata2"}]

for x in dict["name"]:
    print(x)

which obviously does not work. But the main idea is that x should already be the string "testdata" or "testdata2". I want to avoid this:

dict = [{"name": "testdata"}, {"name": "testdata2"}]

for x in dict:
    x = x["name"]

>Solution :

You can’t destructure a dict on assignment, so the only way would be to loop over an iterable that contains only the one value you want, e.g.:

for x in (i['name'] for i in dict):
    ...

or:

from operator import itemgetter

for x in map(itemgetter('name'), dict):
    ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading