473,387 Members | 1,641 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Add two dicts

I have some code like this...

self.write(
'''
lots of stuff here with %(these)s named expressions
'''
% vars(self)
)

Then I wanted to add an item to the dict vars(self), so I tried :

vars(self)+{'x':'123','y':'345'}

This doesn't work, perhaps because no one could decide what should happen
to keys which already exist in the dict? (I'd say throw an exception).

Can I add two dicts in a way which is not cumbersome to the above % string
operation? Is this another case of writing my own function, or does a
builtin (or similar) already exist for this?

Jul 18 '05 #1
12 8976
On Fri, Aug 29, 2003 at 04:11:09AM +0000, Afanasiy wrote:
[ ... ]
Then I wanted to add an item to the dict vars(self), so I tried :

vars(self)+{'x':'123','y':'345'}

This doesn't work, perhaps because no one could decide what should happen
to keys which already exist in the dict? (I'd say throw an exception).

Can I add two dicts in a way which is not cumbersome to the above % string
operation? Is this another case of writing my own function, or does a
builtin (or similar) already exist for this?


You can use dict.update(), however, this works in place, so you'll have
to do it outside of the actual string% statement.

d = {"a": 1, "b": 2}
d.update({'x':'123','y':'345'})

print "%(..)s %(..)d ..." % d

--
m a c k s t a n n mack @ incise.org http://incise.org
So, what's with this guy Gideon, anyway?
And why can't he ever remember his Bible?

Jul 18 '05 #2
Afanasiy wrote:
Can I add two dicts in a way which is not cumbersome to the above %
string
operation? Is this another case of writing my own function, or does a
builtin (or similar) already exist for this?


combinedDict = aDict.copy()
combinedDict.update(anotherDict)

If that's cumbersome, don't really know what you'd consider
non-cumbersome.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \ The revolution will not televised
\__/ Public Enemy
Jul 18 '05 #3
On Thu, 28 Aug 2003 22:07:06 -0700, Erik Max Francis <ma*@alcyone.com>
wrote:
Afanasiy wrote:
Can I add two dicts in a way which is not cumbersome to the above %
string
operation? Is this another case of writing my own function, or does a
builtin (or similar) already exist for this?


combinedDict = aDict.copy()
combinedDict.update(anotherDict)

If that's cumbersome, don't really know what you'd consider
non-cumbersome.


Don't really know if you're asking, but :

vars(self)+{'x':'123','y':'345'}

I would consider that non-cumbersome. ;-)

My only guess why that doesn't exist is that no one decided what to do on
like keys. Use existing, overwrite, or throw exception (my preference).
Jul 18 '05 #4
Afanasiy wrote:
On Thu, 28 Aug 2003 22:07:06 -0700, Erik Max Francis <ma*@alcyone.com>
wrote:
Afanasiy wrote:
Can I add two dicts in a way which is not cumbersome to the above %
string
operation? Is this another case of writing my own function, or does a
builtin (or similar) already exist for this?
combinedDict = aDict.copy()
combinedDict.update(anotherDict)

If that's cumbersome, don't really know what you'd consider
non-cumbersome.


Don't really know if you're asking, but :

vars(self)+{'x':'123','y':'345'}

I would consider that non-cumbersome. ;-)


So, what about:

def dict_add(adict, another):
result = adict.copy()
result.update(another)
return result

and then dict_add(vars(self), {'x':'123','y':'345'}) ? But in fact
you can do even better...:

def dad(_adict, _another={}, **_yetmore):
result = _adict.copy()
result.update(_another)
result.update(_yetmore)
return result

or in 2.3:

def dad(_adict, _another={}, **_yetmore):
result = _adict.copy()
result.update(dict(_another, **_yetmore))
return result
and now, dad(vars(self), x='123', y='345') -- ain't that even
LESS cumbersome? You can't do that with the syntax of + (no
keyword arguments)

Incidentally, in 2.3 you can ALSO spell your desired
adict+anotherdict
as
dict(adict, **anotherdict)
My only guess why that doesn't exist is that no one decided what to do on
like keys. Use existing, overwrite, or throw exception (my preference).


The semantics of all the existing ways of spelling dictionary addition
and the like (update method, **kwds argument to dict in 2.3) have the
second argument 'override' the first. A fast way to check that two
dicts don't overlap (or perhaps more generally to get the list of the
keys in which they do overlap) might be more generally useful, as well
as allowing the diagnostics you want to be produced effectively. Still,
as long as you're writing a function for the addition it's easy and
fast to check for non-overlap:

def dad(_adict, _another={}, **_yetmore):
result = _adict.copy()
result.update(dict(_another, **_yetmore))
if len(result)!=len(_adict)+len(_another)+len(_yetmor e):
raise ValueError, "Overlapping keys on dict addition"
return result
Alex

Jul 18 '05 #5
Afanasiy wrote:
I have some code like this...

self.write(
'''
lots of stuff here with %(these)s named expressions
'''
% vars(self)
)

Then I wanted to add an item to the dict vars(self), so I tried :

vars(self)+{'x':'123','y':'345'}

This doesn't work, perhaps because no one could decide what should happen
to keys which already exist in the dict? (I'd say throw an exception).

Can I add two dicts in a way which is not cumbersome to the above % string
operation? Is this another case of writing my own function, or does a
builtin (or similar) already exist for this?


In Python 2.3, you can, if you wish, code:

self.write(
'''
lots of stuff here with %(these)s named expressions
'''
% dict(vars(self), x='123', y='345')
)

thanks to the new feature of dict of allowing a **kwds argument (with
the 'obvious' semantics, however: named keys override keys already
present in the first argument -- if you need to diagnose overlap and
raise an exception thereupon, you'll have to do that separately).

More generally, if you had an existing dict D you wanted to "add" to
vars(self), rather than a literal, you could code:

self.write(
'''
lots of stuff here with %(these)s named expressions
'''
% dict(vars(self), **D)
)
Alex

Jul 18 '05 #6
Afanasiy <ab********@hotmail.com> wrote in message news:<86********************************@4ax.com>. ..
I have some code like this...

self.write(
'''
lots of stuff here with %(these)s named expressions
'''
% vars(self)
)

Then I wanted to add an item to the dict vars(self), so I tried :

vars(self)+{'x':'123','y':'345'}

This doesn't work, perhaps because no one could decide what should happen
to keys which already exist in the dict? (I'd say throw an exception).

Can I add two dicts in a way which is not cumbersome to the above % string
operation? Is this another case of writing my own function, or does a
builtin (or similar) already exist for this?


Here is a possibile solution:

class attributes(dict):
def __init__(self,obj):
if isinstance(obj,dict):
self.update(obj)
elif hasattr(obj,'__dict__'):
self.update(obj.__dict__)
else:
raise TypeError("Dictionary or object with a __dict__ required")
def __add__(self,other):
self.update(other)
return self.__class__(self)
__radd__=__add__

class C(object):
def __init__(self,x,y):
self.x=x
self.y=y
c=C(1,2)
print attributes(c)
print attributes(c)+{'z':3}
print {'z':3}+attributes(c)
Michele Simionato, Ph. D.
Mi**************@libero.it
http://www.phyast.pitt.edu/~micheles
--- Currently looking for a job ---

http://www.strakt.com/dev_talks.html

http://www.ibm.com/developerworks/li...a2/?ca=dnt-434
Jul 18 '05 #7
On 29 Aug 2003 05:40:15 -0700, rumours say that mi**@pitt.edu (Michele
Simionato) might have written:

[snip]
def __add__(self,other):
self.update(other)
return self.__class__(self)


hm... I am not sure about this; it's not iadd, so you shouldn't modify
self.

Perhaps you should (untested):
def __add__(self, other):
temp = self.copy()
temp.update(other)
return temp
--
TZOTZIOY, I speak England very best,
Microsoft Security Alert: the Matrix began as open source.
Jul 18 '05 #8
Christos "TZOTZIOY" Georgiou <tz**@sil-tec.gr> wrote in message news:<me********************************@4ax.com>. ..
On 29 Aug 2003 05:40:15 -0700, rumours say that mi**@pitt.edu (Michele
Simionato) might have written:

[snip]
def __add__(self,other):
self.update(other)
return self.__class__(self)


hm... I am not sure about this; it's not iadd, so you shouldn't modify
self.

Perhaps you should (untested):
def __add__(self, other):
temp = self.copy()
temp.update(other)
return temp


As you wish ;)

Michele Simionato, Ph. D.
Mi**************@libero.it
http://www.phyast.pitt.edu/~micheles
--- Currently looking for a job ---
Jul 18 '05 #9
"Alex Martelli" <al***@aleax.it> wrote in message
news:Bj*******************@news1.tin.it...
Afanasiy wrote:
On Thu, 28 Aug 2003 22:07:06 -0700, Erik Max Francis <ma*@alcyone.com>
wrote:
Afanasiy wrote:

Can I add two dicts in a way which is not cumbersome to the above % string
operation? Is this another case of writing my own function, or does a builtin (or similar) already exist for this?

combinedDict = aDict.copy()
combinedDict.update(anotherDict)

If that's cumbersome, don't really know what you'd consider
non-cumbersome.


Don't really know if you're asking, but :

vars(self)+{'x':'123','y':'345'}

I would consider that non-cumbersome. ;-)


So, what about:

def dict_add(adict, another):
result = adict.copy()
result.update(another)
return result

and then dict_add(vars(self), {'x':'123','y':'345'}) ? But in fact
you can do even better...:

.... lots of other good ideas...

But what about something like this:
class xdict(dict): .... def __add__(self,dict2):
.... result = self.copy()
.... result = result.update(dict2)
....

I was hoping that would allow: a=xdict({'y': 456, 'x': 111})
b=xdict({'y': 444, 'z': 789})
a+b


but instead of the result which I hoped for, I get the following:

Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: unsupported operand type(s) for +: 'xdict' and 'xdict'

So I can't implement '+' operator for dictionaries - why not?

--
Greg

Jul 18 '05 #10
"Greg Brunet" <gr********@NOSPAMsempersoft.com> wrote in message
news:vl************@corp.supernews.com...
But what about something like this:
class xdict(dict): ... def __add__(self,dict2):
... result = self.copy()
... result = result.update(dict2)
...

I was hoping that would allow: a=xdict({'y': 456, 'x': 111})
b=xdict({'y': 444, 'z': 789})
a+b


but instead of the result which I hoped for, I get the following:

Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: unsupported operand type(s) for +: 'xdict' and 'xdict'

So I can't implement '+' operator for dictionaries - why not?

Ooops - that should have been:
return result.update(dict2)

in the last line, but still, shouldn't that have mapped the "+" operator
for xdict objects?

--
Greg

Jul 18 '05 #11
"Greg Brunet" <gr********@NOSPAMsempersoft.com> wrote in message
news:vl***********@corp.supernews.com...
"Greg Brunet" <gr********@NOSPAMsempersoft.com> wrote in message
news:vl************@corp.supernews.com...
But what about something like this:
>> class xdict(dict):

... def __add__(self,dict2):
... result = self.copy()
... result = result.update(dict2)


.... I was getting sloppy in the interactive mode. Instead I did this &
it seems to work properly:
class xdict(dict):
def add(self,dict2):
result = self.copy()
result.update(dict2)
return result

def __add__(self,dict2):
result = self.copy()
result.update(dict2)
return result

def __iadd__(self,dict2):
self.update(dict2)
return self

a=xdict({'x':1})
b=xdict({'y':2})
print
print "Add:", a.add(b)
print "+:", a+b
print "a:",a,"b:",b
a+=b
print "+= (a=):", a

Results:
Add: {'y': 2, 'x': 1}
+: {'y': 2, 'x': 1}
a: {'x': 1} b: {'y': 2}
+= (a=): {'y': 2, 'x': 1}
--
Greg

Jul 18 '05 #12

"Greg Brunet" <gr********@NOSPAMsempersoft.com> wrote in message
news:vl************@corp.supernews.com...
"Alex Martelli" <al***@aleax.it> wrote in message
news:Bj*******************@news1.tin.it...
Afanasiy wrote:
On Thu, 28 Aug 2003 22:07:06 -0700, Erik Max Francis <ma*@alcyone.com> wrote:

>Afanasiy wrote:
>
>> Can I add two dicts in a way which is not cumbersome to the above %>> string
>> operation? Is this another case of writing my own function, or does a>> builtin (or similar) already exist for this?
>
>combinedDict = aDict.copy()
>combinedDict.update(anotherDict)
>
>If that's cumbersome, don't really know what you'd consider
>non-cumbersome.

Don't really know if you're asking, but :

vars(self)+{'x':'123','y':'345'}

I would consider that non-cumbersome. ;-)
So, what about:

def dict_add(adict, another):
result = adict.copy()
result.update(another)
return result

and then dict_add(vars(self), {'x':'123','y':'345'}) ? But in fact
you can do even better...:

... lots of other good ideas...

But what about something like this:
class xdict(dict): ... def __add__(self,dict2):
... result = self.copy()
... result = result.update(dict2)
...

I was hoping that would allow: a=xdict({'y': 456, 'x': 111})
b=xdict({'y': 444, 'z': 789})
a+b


but instead of the result which I hoped for, I get the following:

Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: unsupported operand type(s) for +: 'xdict' and 'xdict'

So I can't implement '+' operator for dictionaries - why not?


The special functions can only be defined in the class
definition. They cannot be added afterwards. This is a
compiler optimization to avoid having to do dictionary
lookups on every operator.

If you want to do this, subclass dict.

John Roth
--
Greg

Jul 18 '05 #13

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

Similar topics

1
by: Kwikrick | last post by:
When calling str() on a sequence or dict object, the elements of the sequence/dict will be represented as if their __repr__ method was called. Why is this? Wouldn't it be more consistent when...
9
by: rbt | last post by:
What's a good way to write a dictionary out to a file so that it can be easily read back into a dict later? I've used realines() to read text files into lists... how can I do the same thing with...
12
by: Guyon Morée | last post by:
Hi all, I'm using simple classes as a container of named values and I'm instantiating a lot of them in a very short time. i was wondering if there is any benefit in using dicts instead from a...
6
by: bearophileHUGS | last post by:
I have found that in certain situations ordered dicts are useful. I use an Odict class written in Python by ROwen that I have improved and updated some for personal use. So I'm thinking about a...
12
by: Alan Isaac | last post by:
This discussion ended abruptly, and I'd like to see it reach a conclusion. I will attempt to synthesize Bill and Carsten's proposals. There are two proposed patches. The first is to...
0
by: Chris Rebert | last post by:
On Thu, Oct 16, 2008 at 12:19 PM, John Townsend <jtownsen@adobe.comwrote: Right, this clobbers the existing entry with this new blank one. This is evidenced by the fact that you're performing an...
4
by: John Townsend | last post by:
Joe had a good point! Let me describe what problem I'm trying to solve and the list can recommend some suggestions. I have two text files. Each file contains data like this: Test file 1234 4567...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...

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.