且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

创建具有相同键的字典列表?

更新时间:2022-05-13 23:22:43

当您将字典 person 附加到列表 people 时,您只是附加了对字典的引用到列表,所以列表最终只包含对 SAME 字典的引用.

When you append the dictionary person to the list people you are just appending a reference to the dictionary to the list, so the list ends up containing just references to the SAME dictionary.

由于每次循环都会用新值覆盖字典,因此列表最后只包含对您添加的最后一个人的引用.

Since each time through the loop you overwrite the dictionary with new values, at the end the list contains just references to the last person you appended.

您需要做的是为每个人创建一个新词典,例如:

What you need to do is create a new dictionary for every person, for example:

for human in humans:
    number_people, people_data = People.data()
    person = dict()
    person['name'] = human.name
    person['age'] = human.age
    person['Sex'] = human.name
    people.append(person)