Difference between list() and [] with dictionaries

Ned Deily nad at acm.org
Fri May 15 22:46:12 EDT 2009


In article 
<fe3354e50905151817ie4df792hebec03ae42eca25c at mail.gmail.com>,
 Sam Tregar <sam at tregar.com> wrote:
> Can anyone explain why this creates a list containing a
> dictionary:
>   [{'a': 'b', 'foo': 'bar'}] 
> But this creates a list of keys of the dictionary:
>   list({ "a": "b", "foo": "bar" })

The first example is a list, expressed as a list display literal, 
containing one object: a dictionary, expressed as a dictionary display 
literal.

<http://docs.python.org/reference/expressions.html#atoms>

The second example is a call to the built-in function "list", which 
takes a single iterable as an argument and returns "a list whose items 
are the same and in the same order as iterableŒs items".  In this case, 
that single argument is a dictionary.  In an iteration context, the 
iterator obtained for a dictionary iterates over the dictionary's keys.  
The second example is essentially shorthand for:

    list({ "a": "b", "foo": "bar" }.iterkeys())

<http://docs.python.org/library/functions.html#list>
<http://docs.python.org/library/stdtypes.html#mapping-types-dict>

-- 
 Ned Deily,
 nad at acm.org




More information about the Python-list mailing list