Why this list of dictionaries doesn't work?

Previous Topic Next Topic
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

Why this list of dictionaries doesn't work?

Steven D'Aprano-8
On Fri, 19 Jun 2015 03:57 am, Gilcan Machado wrote:

> Hi,
> I'm trying to write a list of dictionaries like:
> people = (
>          {'name':'john', 'age':12} ,
>          {'name':'kacey', 'age':18}
>     )
> I've thought the code below would do the task.

Why don't you just use exactly what you have above? Just change the round
brackets (parentheses) to square brackets to change people from a tuple to
a list:

people = [{'name': 'john', 'age': 12}, {'name': 'kacey', 'age': 18}]

and you now have a list of two dicts.

> But it doesn't work.

What does it do? Does the computer catch fire? Blue Screen Of Death? Does
Python crash, or start printing "All work and no play makes Jack a dull
boy?" over and over again?


You need to explain what you expected to happen and what actually happened,
not just "it doesn't work".

> And if I "print(people)" what I get is not the organize data structure
> like above.

Remember that Python doesn't *pretty-print* lists or dicts by default. If
you print people, you'll get all the information, but it may not be
displayed in what you consider a particularly pleasing or organized manner:

py> people = [{'name': 'john', 'age': 12}, {'name': 'kacey', 'age': 18}]
py> print(people)
[{'age': 12, 'name': 'john'}, {'age': 18, 'name': 'kacey'}]

If you want it displayed as in your original sample, you will need to write
your own print function.

> #!/usr/bin/env python
> from collections import defaultdict
> person = defaultdict(dict)
> people = list()
> person['name'] = 'jose'
> person['age'] = 12
> people.append(person)

This is a little different from what you have above. It uses a defaultdict
instead of a regular dict, I presume you have some good reason for that.

> person['name'] = 'kacey'
> person['age'] = 18

This, however, if where you go wrong. You're not creating a second dict, you
are modifying the existing one. When you modify a dict, you modify it
everywhere it appears. So it doesn't matter whether you look at the
variable person, or if you look at the list people containing that dict,
you see the same value:


Both print the same thing, because they are the same dict (not mere copies).

Another way to put it, Python does *not* copy the dict when you insert it
into a list. So whether you look at people or person[0], you are looking at
the same object.

> people.append(person)

And now you append the same dict to the list, so it is in the list twice.
Now you have:


being three different ways to refer to the same dict, not three different