> From: steve+comp.lang.pyt...@pearwood.info > Subject: Re: Beginner question > Date: Tue, 4 Jun 2013 12:25:27 +0000 > To: python-list@python.org > > 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?
Indeed! But that form isn't economically viable as you noted. > > 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} Awesome! Now I can do it just like that: >>> dict([(chr(ord('a')+x),x) for x in range(2)]) {'a': 0, 'b': 1} Thanks a lot! ;)
-- http://mail.python.org/mailman/listinfo/python-list