How can I add two dictionaries into one?
E.g.
a={'a:1}
b={'b':2}
I need
the result {'a':1,'b':2}.
Is it possible?
Thank you
L. 13 1063
Lad wrote:
How can I add two dictionaries into one?
E.g.
a={'a:1}
b={'b':2}
I need
the result {'a':1,'b':2}.
Is it possible?
Thank you
L.
Yes, use update. Beware that this modifies a dictionary in place rather
than returning a new dictionary.
>>a={'a':1} b={'b':2} a.update(b) a
{'a': 1, 'b': 2}
Gary Herron
How can I add two dictionaries into one?
E.g.
a={'a:1}
b={'b':2}
I need
the result {'a':1,'b':2}.
>>a.update(b) a
{'a':1,'b':2}
-tkc
dict(a.items() + b.items())
Lad wrote:
How can I add two dictionaries into one?
E.g.
a={'a:1}
b={'b':2}
I need
the result {'a':1,'b':2}.
Is it possible?
On Wed, 18 Oct 2006 08:24:27 -0700, Lad wrote:
How can I add two dictionaries into one?
E.g.
a={'a:1}
b={'b':2}
I need
the result {'a':1,'b':2}.
Is it possible?
What should the result be if both dictionaries have the same key?
a={'a':1, 'b'=2}
b={'b':3}
should the result be:
{'a':1, 'b'=2} # keep the existing value
{'a':1, 'b'=3} # replace the existing value
{'a':1, 'b'=[2, 3]} # keep both values
or something else?
Other people have already suggested using the update() method. If you want
more control, you can do something like this:
def add_dict(A, B):
"""Add dictionaries A and B and return a new dictionary."""
C = A.copy() # start with a copy of A
for key, value in B.items():
if C.has_key(key):
raise ValueError("duplicate key '%s' detected!" % key)
C[key] = value
return C
--
Steven.
Tim Chase wrote:
How can I add two dictionaries into one?
E.g.
a={'a:1}
b={'b':2}
I need
the result {'a':1,'b':2}.
>>a.update(b)
>>a
{'a':1,'b':2}
-tkc
Thank you ALL for help.
However It does not work as I would need.
Let's suppose I have
a={'c':1,'d':2}
b={'c':2}
but
a.update(b)
will make
{'c': 2, 'd': 2}
and I would need
{'c': 3, 'd': 2}
(because `c` is 1 in `a` dictionary and `c` is 2 in `b` dictionary, so
1+2=3)
How can be done that?
Thank you for the reply
L
However It does not work as I would need.
Let's suppose I have
a={'c':1,'d':2}
b={'c':2}
but
a.update(b)
will make
{'c': 2, 'd': 2}
and I would need
{'c': 3, 'd': 2}
Ah...a previously omitted detail.
There are likely a multitude of ways to do it. However, the one
that occurs to me off the top of my head would be something like
dict((k, a.get(k, 0) + b.get(k, 0)) for k in a.keys()+b.keys())
If the sets are huge, you can use itertools
>>from itertools import chain dict((k, a.get(k, 0) + b.get(k, 0)) for k in
chain(a.keys(),b.keys()))
{'c': 3, 'd': 2}
which would reduce the need for creating the combined dictionary,
only to throw it away.
-tkc
Steven,
Thank you for your reply and question.
>
What should the result be if both dictionaries have the same key?
The answer: the values should be added together and assigned to the key
That is
{'a':1, 'b':5}
( from your example below)
Is there a solution?
Thanks for the reply
L.
>
a={'a':1, 'b'=2}
b={'b':3}
should the result be:
{'a':1, 'b'=2} # keep the existing value
{'a':1, 'b'=3} # replace the existing value
{'a':1, 'b'=[2, 3]} # keep both values
or something else?
Other people have already suggested using the update() method. If you want
more control, you can do something like this:
def add_dict(A, B):
"""Add dictionaries A and B and return a new dictionary."""
C = A.copy() # start with a copy of A
for key, value in B.items():
if C.has_key(key):
raise ValueError("duplicate key '%s' detected!" % key)
C[key] = value
return C
--
Steven.
Lad wrote:
Let's suppose I have
a={'c':1,'d':2}
b={'c':2}
but
a.update(b)
will make
{'c': 2, 'd': 2}
and I would need
{'c': 3, 'd': 2}
(because `c` is 1 in `a` dictionary and `c` is 2 in `b` dictionary, so
1+2=3)
How can be done that?
dict([(k, a.get(k, 0) + b.get(k,0)) for k in set(a.keys() + b.keys())])
Lad wrote:
The answer: the values should be added together and assigned to the key
That is
{'a':1, 'b':5}
( from your example below)
Is there a solution?
have you tried coding a solution and failed, or are you just expecting
people to code for free?
</F>
On Wed, 18 Oct 2006 09:31:50 -0700, Lad wrote:
>
Steven,
Thank you for your reply and question.
>> What should the result be if both dictionaries have the same key?
The answer: the values should be added together and assigned to the key
That is
{'a':1, 'b':5}
( from your example below)
Is there a solution?
Of course there is a solution. You just have to program it.
Look again at my example code before:
def add_dict(A, B):
"""Add dictionaries A and B and return a new dictionary."""
C = A.copy() # start with a copy of A
for key, value in B.items():
if C.has_key(key):
raise ValueError("duplicate key '%s' detected!" % key)
C[key] = value
return C
Can you see how to modify this function to do what you want?
(Hint: instead of raising a ValueError exception, you want to do something
else.)
--
Steven.
Fredrik Lundh wrote:
Lad wrote:
>The answer: the values should be added together and assigned to the key That is {'a':1, 'b':5} ( from your example below)
Is there a solution?
have you tried coding a solution and failed, or are you just expecting
people to code for free?
</F>
Right. This thread begins to look like someone with a homework
assignment asking for code rather than attempting to try programming it
up himself. I was happy to answer the first plea for help, but I'd be
leery of providing any actual code.
Gary Herron
Steven,
Thank you for help;
Here is a code that works in a way I need
A={'c':1,'d':2,'e':3,'f':2}
B={'c':2,'e':1}
if len(A)>=len(B):
Delsi=B
C = A.copy()
else:
Delsi=A
C = B.copy()
for key, value in Delsi.items():
if C.has_key(key):
C[key]=C[key]+value
else:
C[key]=value
How easy :-)
Regards,
L.
Steven D'Aprano wrote:
On Wed, 18 Oct 2006 09:31:50 -0700, Lad wrote:
Steven,
Thank you for your reply and question.
>
What should the result be if both dictionaries have the same key?
The answer: the values should be added together and assigned to the key
That is
{'a':1, 'b':5}
( from your example below)
Is there a solution?
Of course there is a solution. You just have to program it.
Look again at my example code before:
def add_dict(A, B):
"""Add dictionaries A and B and return a new dictionary."""
C = A.copy() # start with a copy of A
for key, value in B.items():
if C.has_key(key):
raise ValueError("duplicate key '%s' detected!" % key)
C[key] = value
return C
Can you see how to modify this function to do what you want?
(Hint: instead of raising a ValueError exception, you want to do something
else.)
--
Steven.
This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Kerry Neilson |
last post by:
Hi,
Really hung up on this one. I'm trying to get all the fields of a
dictionary to be unique for each class:
class A {
my_dict =
dict_entry = { 'key1':0, 'key2':0 }
__init__(self):
for...
|
by: Till Plewe |
last post by:
Is there a way to speed up killing python from within a python program?
Sometimes shutting down takes more than 10 times as much time as the actual
running of the program.
The programs are...
|
by: Frohnhofer, James |
last post by:
My initial problem was to initialize a bunch of dictionaries at the start of a
function.
I did not want to do
def fn():
a = {}
b = {}
c = {}
. . .
z = {}
|
by: Shivram U |
last post by:
Hi,
I want to store dictionaries on disk. I had a look at a few modules
like bsddb, shelve etc. However would it be possible for me to do the
following
hash = where the key is an int and not...
|
by: Christoph Zwerschke |
last post by:
This is probably a FAQ, but I dare to ask it nevertheless since I
haven't found a satisfying answer yet: Why isn't there an "ordered
dictionary" class at least in the standard list? Time and again...
|
by: David Pratt |
last post by:
Hi. I like working with lists of dictionaries since order is preserved
in a list when I want order and the dictionaries make it explicit what
I have got inside them. I find this combination very...
|
by: Faisal Alquaddoomi |
last post by:
Hello,
I'm having a bit of trouble isolating my scripts from each other in my
embedded Python interpreter, so that their global namespaces don't get
all entangled. I've had some luck with...
|
by: placid |
last post by:
Hi all,
Just wondering if anyone knows how to pop up the dialog that windows
pops up when copying/moving/deleting files from one directory to
another, in python ?
Cheers
|
by: Edwin.Madari |
last post by:
by the way, iterating over bar will throw KeyError if that key does not exist in foo. to see that in action, simply set another key in bar after copy.deepcopy stmt in this example..
bar = 0
and...
|
by: cnb |
last post by:
Are dictionaries the same as hashtables?
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
by: ArrayDB |
last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: Defcon1945 |
last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
|
by: af34tf |
last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
| |