Home > Software engineering >  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?

Time:11-22

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.

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"]

CodePudding user response:

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):
    ...

CodePudding user response:

You won't get around calling the key for each element but you can do it in a list comprehension to convert your list of dictionaries to a list of 'name' elements and then loop through that:

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

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