创建具有相同键的字典列表? [英] Creating a list of dictionaries with same keys?

查看:34
本文介绍了创建具有相同键的字典列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个列表,其中包含 x 个字典,所有字典都包含相同的键,但在 for 循环中具有不同的值:

I wanted to create a list that contains x amount of dictionaries all containing the same keys but with different values that's made in a for loop:

类似的东西

[{'name': Brenda, 'Age': 22, 'Sex': Female},
 {'name': Jorda, 'Age': 32, 'Sex': Male},
 {'name': Richard, 'Age': 54, 'Sex': Male}]

我的代码是这样的:

people = []
person = {}

humans = gethumans()

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

我的输出是这样的:

[{'name': Richard, 'Age': 54, 'Sex': Male},
 {'name': Richard, 'Age': 54, 'Sex': Male}
 {'name': Richard, 'Age': 54, 'Sex': Male}]

因为字典值被替换而不是添加,它只是附加相同的字典.我该如何解决这个问题?

Since the dictionary values are getting replaced and not added and it's just appending the same dictionary. How can I get around this?

推荐答案

当您将字典 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)

这篇关于创建具有相同键的字典列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆