Bitten by my C/Java experience

Tim Chase python.list at tim.thechases.com
Mon May 4 17:26:30 EDT 2015


On 2015-05-04 21:57, Andrew Cooper wrote:
> On 04/05/2015 18:43, Ian Kelly wrote:
> > 
> > Some other gotchas that aren't necessarily related to C/Java but
> > can be surprising nonetheless:
> > 
> > *    () is a zero-element tuple, and (a, b) is a two-element
> > tuple, but (a) is not a one-element tuple. Tuples are created by
> > commas, not parentheses, so use (a,) instead.
> 
> * {} is an empty set(), not dict().
> 
> Particularly subtle when combined with **kwargs
> 
> $ python3
> Python 3.4.0 (default, Apr 11 2014, 13:05:11)
> [GCC 4.8.2] on linux
> Type "help", "copyright", "credits" or "license" for more
> information.
> >>> def foo(**kwargs):
> ...   return { (k, kwargs[k]) for k in kwargs }
> ...
> >>> foo()
> set()
> >>> foo(a=1)
> {('a', 1)}
> >>>

It's a dict:

Python 3.2.3 (default, Feb 20 2013, 14:44:27) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> type({})
<class 'dict'>


What you're seeing is that your generator creates single-element
tuples in a set constructor (note that your last item isn't
"{'a': 1}". Try instead

>>> def foo(**kwargs):
...     return {k: kwargs[k] for k in kwargs}
... 
>>> foo()
{}
>>> foo(a=42)
{'a': 42}

Note the colons, indicating that it's a dict.  You're using the
dict() syntax:

  dict((k,v) for k,v in some_iter())

-tkc









More information about the Python-list mailing list