python: loop through specific key value

Question:

I’m trying to process following dictionary.

thisdict =  {
    "changes": [
        "abc",
        "cba"
    ],
    "projects": [
         "aaa"
    ],
}

added_change=thisdict["changes"]

for x, y in added_change.items():
  print(added_change)

desired output

abc
cba
Asked By: Mihir

||

Answers:

In the code you show, added_change is a list, not a dict, so it won’t have a .items(). Simply doing the following should work:

for x in added_change:
    print(x)
Answered By: Connor Anderson

You will take the error like this:

AttributeError: 'list' object has no attribute 'items'

Because added_change is a list, not a dictionary and items is used with dictionary.

Your added_change list includes already ['abc', 'cba'], you want to print them line by line, thus, you only need to use print with iteration on your list.

for i in added_change:
    print(i)

Output:

abc
cba
Answered By: Furkan Akdag
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.