Why this list of dictionaries doesn't work?

Gary Herron gherron at digipen.edu
Thu Jun 18 14:27:12 EDT 2015


On 06/18/2015 10: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.
>
> But it doesn't work.

Never say "it doesn't work" on this list.  Tell us what it did, and what 
you expected.  Provide a copy of the full error message. That's much 
more helpful than making us guess.

>
> 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
>
> person = defaultdict(dict)

If you want *two* different dictionaries, you'll have to create *two* of 
them.  You code creates only this one.

> people = list()
>
> person['name'] = 'jose'
> person['age'] = 12
>
> people.append(person)

Here's where you need to create the second one.

>
> person['name'] = 'kacey'
> person['age'] = 18
>
> people.append(person)
>
> for person in people:
>     print( person['nome'] )

Typo here:  'name', not 'nome'.

>
>
>


-- 
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150618/8b88d538/attachment.html>


More information about the Python-list mailing list