Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

python - Creating a list of dictionaries with same keys?

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:

Something like

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

My code is this:

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)

My output is something like this:

[{'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 dicitnary. How can I get around this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...