简体   繁体   English

迭代列表中的字典

[英]Iterating over a dictionary inside a list

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?关于如何解决这个问题的任何想法?

You are append a list .你是 append 一个list That's why when you loop it, it will return you a list .这就是为什么当你循环它时,它会返回一个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"})

dic_list is list of list of dicts in your code. dic_list是代码中字典列表的列表。 dic_list.append - is appending a list of dicts to dic_list dic_list.append - 将字典列表附加到dic_list

Since you want to append multiple dictionaries to your dic_list at a time, you can use list.extend() instead由于您想一次将 append 多个字典添加到您的dic_list中,您可以使用list.extend()代替

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 -这将打印预期的 output -

[{'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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM