Why this list of dictionaries doesn't work?

MRAB python at mrabarnett.plus.com
Thu Jun 18 14:37:40 EDT 2015


On 2015-06-18 18:57, Gilcan Machado wrote:
> Hi,
>
> I'm trying to write a list of dictionaries like:
>
> people = (
>           {'name':'john', 'age':12} ,
>           {'name':'kacey', 'age':18}
>      )
>
That's not a list; it's a tuple. If you want a list, use '[' and ']'.
>
> I've thought the code below would do the task.
>
> But it doesn't work.
>
> And if I "print(people)" what I get is not the organize data structure
> like above.
>
> Thanks of any help!
> []s
> Gilcan
>
> #!/usr/bin/env python
> from collections import defaultdict
>
You don't need a defaultdict, just a normal dict.

This creates an empty defaultdict whose default value is a dict:

> person = defaultdict(dict)
> people = list()
>
This puts some items into the dict:

> person['name'] = 'jose'
> person['age'] = 12
>
This puts the dict into the list:

> people.append(person)
>
This _reuses_ the dict and overwrites the items:

> person['name'] = 'kacey'
> person['age'] = 18
>
This puts the dict into the list again:

> people.append(person)
>
The list 'people' now contains 2 references to the _same_ dict.

> for person in people:
>      print( person['nome'] )

Initially there's no such key as 'nome' (not the spelling), so it
creates one with the default value, a dict.

If you print out the people list, you'll see:

[defaultdict(<class 'dict'>, {'name': 'kacey', 'age': 18, 'nome': {}}), 
defaultdict(<class 'dict'>, {'name': 'kacey', 'age': 18, 'nome': {}})]




More information about the Python-list mailing list