Home > Blockchain >  Iterating over a dictionary inside a list
Iterating over a dictionary inside a list

Time:01-15

dic_list = []

for stuff in range(1):
    dic_list.append([{"Word": "Zawurdo!!!", "Meaning": "Nothing Really", "Synonym": "Nope", "Antonym": "LoL! Does Not exist"}, {"Word": "Duwardooo!!!", "Meaning": "Nothing", "Synonym": "Nope!!!", "Antonym": "Does Not exist"}])
    print(dic_list, "\n")

for i in range(len(dic_list)):
    print(f"Number {i}: ")
    for key, value in dic_list[i].items():
        print(f"{key}: {value}")

Traceback (most recent call last):
  File "c:\Users\ASUS\OneDrive\Desktop\PythonAndMathsForMachineLearning\first.py", line 9, in <module>
    for key, value in dic_list[i].items():
AttributeError: 'list' object has no attribute 'items'

So, this is the code I am trying to run to iterate over my dictionary and access all the values within it. But instead of getting the values, I have encountred an error. Any idea on how to fix this issue?

CodePudding user response:

You are append a list. That's why when you loop it, it will return you a list.

So you have to change it to:

dic_list.append({"Word": "Zawurdo!!!", "Meaning": "Nothing Really", "Synonym": "Nope", "Antonym": "LoL! Does Not exist"})
dic_list.append({"Word": "Duwardooo!!!", "Meaning": "Nothing", "Synonym": "Nope!!!", "Antonym": "Does Not exist"})

CodePudding user response:

dic_list is list of list of dicts in your code. dic_list.append - is appending a list of dicts to dic_list

Since you want to append multiple dictionaries to your dic_list at a time, you can use list.extend() instead

dic_list = []

for stuff in range(1):
    dic_list.extend([{"Word": "Zawurdo!!!", "Meaning": "Nothing Really", "Synonym": "Nope", "Antonym": "LoL! Does Not exist"}, {"Word": "Duwardooo!!!", "Meaning": "Nothing", "Synonym": "Nope!!!", "Antonym": "Does Not exist"}])
    print(dic_list, "\n")

for i in range(len(dic_list)):
    print(f"Number {i}: ")
    for key, value in dic_list[i].items():
        print(f"{key}: {value}")

This prints the expected output of -

[{'Word': 'Zawurdo!!!', 'Meaning': 'Nothing Really', 'Synonym': 'Nope', 'Antonym': 'LoL! Does Not exist'}, {'Word': 'Duwardooo!!!', 'Meaning': 'Nothing', 'Synonym': 'Nope!!!', 'Antonym': 'Does Not exist'}]

Number 0:
Word: Zawurdo!!!
Meaning: Nothing Really
Synonym: Nope
Antonym: LoL! Does Not exist
Number 1:
Word: Duwardooo!!!
Meaning: Nothing
Synonym: Nope!!!
Antonym: Does Not exist
  •  Tags:  
  • Related