Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #92842 > unrolled thread
| Started by | MRAB <python@mrabarnett.plus.com> |
|---|---|
| First post | 2015-06-18 19:37 +0100 |
| Last post | 2015-06-18 19:37 +0100 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Why this list of dictionaries doesn't work? MRAB <python@mrabarnett.plus.com> - 2015-06-18 19:37 +0100
| From | MRAB <python@mrabarnett.plus.com> |
|---|---|
| Date | 2015-06-18 19:37 +0100 |
| Subject | Re: Why this list of dictionaries doesn't work? |
| Message-ID | <mailman.607.1434652666.13271.python-list@python.org> |
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': {}})]
Back to top | Article view | comp.lang.python
csiph-web