Beginner question

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Jun 4 08:25:27 EDT 2013


On Tue, 04 Jun 2013 14:53:29 +0300, Carlos Nepomuceno wrote:

> That's exactly the same!
>>>>dict(**{a:0,b:1})=={a:0,b:1}
> True


Of course it is. Isn't that what you wanted?

It's also a waste of time, because you create a dict literal using {}, 
then unpack it into keyword arguments, then call dict() to create a new 
dict with the same content. Rather like doing this:

n = int(str(42))

only even more expensive.


> Are there any benefits from using dict() instead of {}?

Of course there are. {} can be used for creating dict literals, which 
means you are limited to key/values that you explicitly include. dict(), 
on the other hand, has a rich set of constructor APIs:

py> help(dict)

Help on class dict in module builtins:

class dict(object)
 |  dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v
 |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
 |      in the keyword argument list.  For example:  dict(one=1, two=2)


py> dict(zip('abcd', range(4)), x=23, y=42, z=999)
{'a': 0, 'c': 2, 'b': 1, 'd': 3, 'y': 42, 'x': 23, 'z': 999}


Try doing that with {} alone!



-- 
Steven



More information about the Python-list mailing list