[Tutor] dict() versus {}

wormwood_3 wormwood_3 at yahoo.com
Thu Jan 22 05:14:23 CET 2009


Hmm, looked through the latest docs, in the sections on dictionary types, don't see examples that point to this case well. Can you link to what you had in mind?

 _______________________
Samuel Huckins


Homepage - http://samuelhuckins.com
Tech blog - http://dancingpenguinsoflight.com/
Photos - http://www.flickr.com/photos/samuelhuckins/
AIM - samushack | Gtalk - samushack | Skype - shuckins




________________________________
From: bob gailer <bgailer at gmail.com>
To: wormwood_3 <wormwood_3 at yahoo.com>
Cc: Python Tutorlist <tutor at python.org>
Sent: Wednesday, January 21, 2009 11:02:35 PM
Subject: Re: [Tutor] dict() versus {}

wormwood_3 wrote: 
When
creating a list of dictionaries through a loop, I ran into a strange
issue. I'll let the code talk:

>>> l = 'i am a special new list'.split()
>>> t = []
>>> for thing in l:
...     t.append({thing: 1})
... 
>>> t
[{'i': 1}, {'am': 1}, {'a': 1}, {'special': 1}, {'new': 1}, {'list': 1}]

This is what I expected. {} says to make a dictionary. Thing, not being
quoted, is clearing a variable, which needs to be evaluated and used as
the key.

>>> t = []
>>> for thing in l:
...     t.append(dict(thing=1))
... 
>>> t
[{'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1},
{'thing': 1}]

This was what threw me. Why would the dict() function not evaluate
thing? How can it take it as a literal string without quotes?
I suggest you look dict up in the Python documentation. There it shows
the result you got as an example. When in doubt read the manual.


-- 
Bob Gailer
Chapel Hill NC
919-636-4239
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090121/bfaded2e/attachment.htm>


More information about the Tutor mailing list