idiomatic way of merging two dictionaries

View: New views
3 Messages — Rating Filter:   Alert me  

idiomatic way of merging two dictionaries

by amit sethi :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi , I am trying to merge(I am not sure if that is the right term) dictionaries like this

dict1 ={'a':4,'b':3,'v':7,'h':4}
dict2={'a':5,'v':4,'k':3}
dict3 would be {'a':[4,5],'b':[3,4],'v':[7,4],'k':[0,3],'h':[4,0]}

--
A-M-I-T S|S

_______________________________________________
Tutor maillist  -  Tutor@...
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Re: idiomatic way of merging two dictionaries

by Alan Gauld :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message


"Amit Sethi" <amit.pureenergy@...> wrote

> Hi , I am trying to merge(I am not sure if that is the right term)
> dictionaries like this
>
> dict1 ={'a':4,'b':3,'v':7,'h':4}
> dict2={'a':5,'v':4,'k':3}
> dict3 would be {'a':[4,5],'b':[3,4],'v':[7,4],'k':[0,3],'h':[4,0]}

I don't know how "idiomatic" it is but I'd probably just go for a for loop

dict3 = {}
for key in set(dict1.keys()+dict2.keys()):    # get the unique keys
     dict3[key] = [dict1.get(key,0),dict2.get(key,0)]

I suspect that in Python 3 you could use the new dict notation
to do it slightly more neatly.

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

_______________________________________________
Tutor maillist  -  Tutor@...
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Re: idiomatic way of merging two dictionaries

by Lie Ryan :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Amit Sethi wrote:
> Hi , I am trying to merge(I am not sure if that is the right term)
> dictionaries like this
>
> dict1 ={'a':4,'b':3,'v':7,'h':4}
> dict2={'a':5,'v':4,'k':3}
> dict3 would be {'a':[4,5],'b':[3,4],'v':[7,4],'k':[0,3],'h':[4,0]}
>

I can't see what you're trying to do there. is 'b' supposed to be 3,4
or 0,3?

And is th ordering between the list (i.e. 'a':[4, 5] and 'a':[5, 4])
significant?

_______________________________________________
Tutor maillist  -  Tutor@...
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor