473,573 Members | 2,870 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dict literals vs dict(**kwds)

Although I consider dict(**kwds) as one of the few unfortunate design
choices in python since it prevents the future addition of useful
keyword arguments (e.g a default value or an orderby function), I've
been finding myself lately using it sometimes instead of dict literals,
for no particular reason. Is there any coding style consensus on when
should dict literals be preferred over dict(**kwds) and vice versa ?

George

May 23 '06 #1
15 2433
George Sakkis a écrit :
Although I consider dict(**kwds) as one of the few unfortunate design
choices in python since it prevents the future addition of useful
keyword arguments (e.g a default value or an orderby function), I've
been finding myself lately using it sometimes instead of dict literals,
for no particular reason. Is there any coding style consensus on when
should dict literals be preferred over dict(**kwds) and vice versa ?


using dict literals means that you'll always have a builtin dict - you
cannot dynamically select another dict-like class. OTHO, you can only
use valid python identifiers as keys with dict(**kw).
May 23 '06 #2
Bruno Desthuilliers wrote:
George Sakkis a écrit :
Although I consider dict(**kwds) as one of the few unfortunate design
choices in python since it prevents the future addition of useful
keyword arguments (e.g a default value or an orderby function), I've
been finding myself lately using it sometimes instead of dict literals,
for no particular reason. Is there any coding style consensus on when
should dict literals be preferred over dict(**kwds) and vice versa ?


using dict literals means that you'll always have a builtin dict - you
cannot dynamically select another dict-like class. OTHO, you can only
use valid python identifiers as keys with dict(**kw).


This is all good but doesn't answer my original question: under which
circumstances (if any) would {'name':'Mike, 'age':23} be preferred
over dict(name='Mike ', age=23) and vice versa, or if it's just a matter
of taste, similar to using single vs double quote for string literals
(when both are valid of course).

George

May 23 '06 #3
George Sakkis <ge***********@ gmail.com> wrote:
Bruno Desthuilliers wrote:
George Sakkis a écrit :
Although I consider dict(**kwds) as one of the few unfortunate design
choices in python since it prevents the future addition of useful
keyword arguments (e.g a default value or an orderby function), I've
been finding myself lately using it sometimes instead of dict literals,
for no particular reason. Is there any coding style consensus on when
should dict literals be preferred over dict(**kwds) and vice versa ?


using dict literals means that you'll always have a builtin dict - you
cannot dynamically select another dict-like class. OTHO, you can only
use valid python identifiers as keys with dict(**kw).


This is all good but doesn't answer my original question: under which
circumstances (if any) would {'name':'Mike, 'age':23} be preferred
over dict(name='Mike ', age=23) and vice versa, or if it's just a matter
of taste, similar to using single vs double quote for string literals
(when both are valid of course).


My personal favorite style is always to call the type when applicable
(and reasonably forecast to _remain_ applicable in future code changes),
because readability benefits.
Alex
May 24 '06 #4
George Sakkis wrote:
Bruno Desthuilliers wrote:

George Sakkis a écrit :
Although I consider dict(**kwds) as one of the few unfortunate design
choices in python since it prevents the future addition of useful
keyword arguments (e.g a default value or an orderby function), I've
been finding myself lately using it sometimes instead of dict literals,
for no particular reason. Is there any coding style consensus on when
should dict literals be preferred over dict(**kwds) and vice versa ?
using dict literals means that you'll always have a builtin dict - you
cannot dynamically select another dict-like class. OTHO, you can only
use valid python identifiers as keys with dict(**kw).

This is all good but doesn't answer my original question:


I thought it did - at least partly.
under which
circumstances (if any) would {'name':'Mike, 'age':23} be preferred
over dict(name='Mike ', age=23)
When you're sure you want a builtin dict (not any other dictlike) and/or
some keys are invalid Python identifiers.
and vice versa,
When all your keys are valid Python identifiers, and you may want to use
another dict-like instead of the builtin dict. It's easy to replace the
dict() factory in a function, class, or whole module :

class MyDict(...):
# dict-like class

dict = MyDict

then all following calls to dict(**kw) in this namespace will use MyDict
instead of the builtin's one. Can't do that with dict litterals.
or if it's just a matter
of taste,
Partly also, but...
similar to using single vs double quote for string literals
(when both are valid of course).


Nope, this is not so similar, cf above.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
May 24 '06 #5
bruno at modulix wrote:
When all your keys are valid Python identifiers, and you may want to use
another dict-like instead of the builtin dict. It's easy to replace the
dict() factory in a function, class, or whole module :

class MyDict(...):
# dict-like class

dict = MyDict

then all following calls to dict(**kw) in this namespace will use MyDict
instead of the builtin's one. Can't do that with dict litterals.


Hm, as far as I know shadowing the builtins is discouraged. This is not
the same as duck typing, when you may define a function like

def foo(dict_like_c lass):
return dict_like_class (x=1,y=2).iteri tems()

and call it as foo(MyDict)

In either case, I would guess that for the vast majority of cases the
builtin dicts are just fine and there's no compelling reason for
dict(**kwds). Perhaps it's something that should be reconsidered for
Py3K.

George

May 24 '06 #6
> Hm, as far as I know shadowing the builtins is discouraged.

*accidentally* shadowing builtins is a common Python gotcha - that's
why it's comon here to raise *warnings* about this.

Explicitly and knowingly rebinding a builtin (or any other name FWIW)
*with a compatible object* is something else. Just google for
"monkey-patching". And yes, it *is* an application of duck-typing.
In either case, I would guess that for the vast majority of cases the
builtin dicts are just fine
That's probably why there are so many uses of dict-like objects
(starting with the __dict__ attribute of classes, which is usually a
DictProxy object) and so many helpers to build dict-like objects.
and there's no compelling reason for dict(**kwds).
Yes there is : this *is* the ordinary Python syntax - calling a type to
get an instance of it. The dict-litteral syntax is mostly syntactic
sugar.
Perhaps it's something that should be reconsidered for Py3K


Hopefully not. The fact that you fail to understand why a given feature
exists and how it can be useful is not a reason to ask for arbitrary
restrictions on the language.

May 26 '06 #7
bruno de chez modulix en face wrote:
and there's no compelling reason for dict(**kwds).


Yes there is : this *is* the ordinary Python syntax - calling a type to
get an instance of it. The dict-litteral syntax is mostly syntactic
sugar.


The thing is there are four (at least?) ways to get a dict instance:

In [1]: d1={'name':'mik e', 'age':23}

In [2]: d2=dict(d1)

In [3]: d3=dict(**d1)

In [4]: d4=dict(d1.item s())

In [5]: d1==d2==d3==d4
Out[5]: True

Talk about "there should be one and preferably one obvious way to do
it".

Perhaps it's something that should be reconsidered for Py3K


Hopefully not. The fact that you fail to understand why a given feature
exists and how it can be useful is not a reason to ask for arbitrary
restrictions on the language.


Perhaps you fail to understand that the given feature is
1) redundant (see above).
2) restricting in a more serious sense: the future addition of optional
keyword arguments that affect the dict's behaviour. Google for "default
dict" or "dictionary accumulator".

George

May 26 '06 #8
George Sakkis wrote:
Perhaps you fail to understand that the given feature is
1) redundant (see above).
Yes, but a certain degree of redundancy in the language is inevitable, and
when it exists (as in this case) to make people's life easier it may be a
good thing. Obviously the tradeoff between increasing complexity vs
increasing ease-of-use has to be discussed before such new features are
added, and in this case I believe it was.
2) restricting in a more serious sense: the future addition of optional
keyword arguments that affect the dict's behaviour. Google for "default
dict" or "dictionary accumulator".


There is nothing to stop dictionaries being created using factory functions
(e.g. see dict.fromkeys). So one possible way to implement defaults would
be to extend the dict class with a new classmethod 'withdefault' which
takes a default value as an argument.

However, given that the default argument isn't actually needed during
construction, it doesn't seem to me that it fits either as a constructor
parameter nor a factory method. I don't see why it shouldn't just be set on
an existing dictionary (or dictionary subclass) when you need it.
May 26 '06 #9
Duncan Booth wrote:
George Sakkis wrote:
2) restricting in a more serious sense: the future addition of optional
keyword arguments that affect the dict's behaviour. Google for "default
dict" or "dictionary accumulator".


There is nothing to stop dictionaries being created using factory functions
(e.g. see dict.fromkeys). So one possible way to implement defaults would
be to extend the dict class with a new classmethod 'withdefault' which
takes a default value as an argument.

However, given that the default argument isn't actually needed during
construction, it doesn't seem to me that it fits either as a constructor
parameter nor a factory method. I don't see why it shouldn't just be set on
an existing dictionary (or dictionary subclass) when you need it.


Because I would find

d = dict(default=0)
d['x'] += 3

more elegant than

d = {}
d.withdefault(0 )
d['x'] += 3

YMMV,
George

May 26 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
2168
by: Paradox | last post by:
Why does the following attempts to pass in keywords arguments not work. It would be alot cooler if there was a way to not have to have the function defined with the variable name. It really seems to me that the 3rd function should work. Does anyone know how to accomplish something like this. def testKeywords1 (**kwds): print x def...
699
33526
by: mike420 | last post by:
I think everyone who used Python will agree that its syntax is the best thing going for it. It is very readable and easy for everyone to learn. But, Python does not a have very good macro capabilities, unfortunately. I'd like to know if it may be possible to add a powerful macro system to Python, while keeping its amazing syntax, and if it...
25
2374
by: Steven Bethard | last post by:
So I end up writing code like this a fair bit: map = {} for key, value in sequence: map.setdefault(key, ).append(value) This code basically constructs a one-to-many mapping -- each value that a key occurs with is stored in the list for that key. This code's fine, and seems pretty simple, but thanks to generator
6
1765
by: Rick Morrison | last post by:
Would there be any way to add a method to all dict objects that operated like the .update() method, but also returned a reference to the updated dict? ..update() is clumsy to use inside of list comprehensions and the like. Or am I missing something? Thanks, Rick
49
2782
by: Christopher J. Bottaro | last post by:
I find myself doing the following very often: class Struct: pass .... blah = Struct() blah.some_field = x blah.other_field = y ....
27
2085
by: Ron Adam | last post by:
Hi, I found the following to be a useful way to access arguments after they are passed to a function that collects them with **kwds. class namespace(dict): def __getattr__(self, name): return self.__getitem__(name) def __setattr__(self, name, value): self.__setitem__(name, value) def __delattr__(self, name):
1
3007
by: Luis Zarrabeitia | last post by:
Hi there. I just tried this test: ==== def f(**kwds): print kwds import UserDict d = UserDict.UserDict(hello="world")
6
1494
by: dlists.cad | last post by:
Hi. I am looking for a way to check if some given set of (*args, **kwds) conforms to the argument specification of a given function, without calling that function. For example, given the function foo: def foo(a, b, c): pass and some tuple args and some dict kwds, is there a way to tell if i _could_ call foo(*args, **kwds) without getting...
3
1194
by: srinivasan srinivas | last post by:
Hi, I have written a class which has some attributes. I want to know how do i find out the size of an instance of this class?? class T(object):     def __init__(self, fn_name, *args, **kwds):         self.fn_name = fn_name         self.args = args         self.kwds = kwds Thanks, Srini
0
7686
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8009
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8198
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8060
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5580
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5289
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3731
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2194
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1296
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.