[Tutor] dict() versus {}

Kent Johnson kent37 at tds.net
Thu Jan 22 12:33:27 CET 2009


On Wed, Jan 21, 2009 at 10:54 PM, wormwood_3 <wormwood_3 at yahoo.com> wrote:
> When creating a list of dictionaries through a loop, I ran into a strange
> issue. I'll let the code talk:

>>>> 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?

The call dict(thing=1) is using the standard keyword parameter syntax,
and it handles the keywords the same as any other function call - the
keywords are tokens, not variable names or expressions, and they are
not evaluated.

The current behaviour is consistent with other uses of keyword
arguments. Use your first method if you want to evaluate the key.

Kent


More information about the Tutor mailing list