471,594 Members | 1,230 Online

# merging dictionaries

31
so basically i've written most of the code the only problem that i'm having is that the output that it gives me will not return a key with a different type. It will either return me keys with only int, or only str..for example

Expand|Select|Wrap|Line Numbers
1. def merge_dictionaries(d1, d2):
2.     '''Return a dictionary that is the result of merging the two given
3.     dictionaries. In the new dictionary, the values should be lists. If a key
4.     is in both of the given dictionaries, the value in the new dictionary should
5.     contain both of the values from the given dictionaries, even if they are the
6.     same. '''
7.
8.     d3 = {}
9.     for c in d1:
10.         if c in d2:
11.             d3[c] = [d1[c], d2[c]]
12.         else:
13.             d3[c] = [d1[c]]
14.     print d3
15.
how i tested it is with:

Expand|Select|Wrap|Line Numbers
1. merge_dictionaries({ 1 : 'a', 2 : 9, -8 : 'w'}, {2 : 7, 'x' : 3, 1 : 'a'})
2.
and the out put is:
Expand|Select|Wrap|Line Numbers
1. {-8: ['w'], 1: ['a', 'a'], 2: [9, 7]}
why doesn't it print out the 'x' key and value??
Mar 12 '09 #1
4 2320
bvdet
2,851 Expert Mod 2GB
Because d2 has a key that d1 does not have. You only iterate on d1, so key 'x' is never seen.

-BV
Mar 13 '09 #2
bvdet
2,851 Expert Mod 2GB
Take a look at this:
Expand|Select|Wrap|Line Numbers
1. import copy
2.
3. def merge_dictionaries(d1, d2):
4.     d3 = copy.copy(d1)
5.     for key in d2:
6.         if key in d3:
7.             d3[key] = [d3[key], d2[key]]
8.         else:
9.             d3[key] = [d2[key]]
10.     return d3
11.
12. dd1 = { 1 : 'a', 2 : 9, -8 : 'w'}
13. dd2 = {2 : 7, 'x' : 3, 1 : 'a'}
14. print merge_dictionaries(dd1, dd2)
Mar 13 '09 #3
v13tn1g
31
in this case you imported copy, what is that?
Mar 13 '09 #4
bvdet
2,851 Expert Mod 2GB
@v13tn1g
copy.copy makes a shallow copy of an object. From Python documentation:
"A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original."

This will do the same thing:
Expand|Select|Wrap|Line Numbers
1. d3 = dict(d1.items())
Mar 13 '09 #5