Is there a ways to merge two similar dictionaries, and what happens if the key words clash?

Hi bumsfeld,

Well, the naive solution might be something like this:

a, b = dict(), dict()
a["a_one"], a["a_two"], a["a_three"] = "a1", "a2", "a3"
b["b_one"], b["b_two"], b["b_three"] = "b1", "b2", "b3"
for k in a.keys():
     if b.has_key(k): continue
     else: b[k] = a[k]
print b

After the loop terminates, b has all of a's items, except for the ones where the keys collided. You need to decide for yourself what should happen on key collision - should you raise an Exception? Overwrite the value with a's value? Let b's value stand? Do something else? The answer to these questions is situation-specific.

Hope that helps.

Hi!

a, b = dict(), dict()
a["a_one"], a["a_two"], a["a_three"] = "a1", "a2", "a3"

A very unusual way to create a dictionary :)

Dictionarys have the method update():

>>> d1 = {"a": "a1", "b": "b1"}
>>> d2 = {"c": "c1", "b": "b2"}
>>> d1.update(d2)
>>> d1
{'a': 'a1', 'c': 'c1', 'b': 'b2'}

As you can see, the value of "b" in d1 is updated. If you don't want this, as G-Do said, you have many choices. One is the following:

>>> for k in d2:
...     if k in d1:
...             d1[k] = [d1[k], d2[k]]
...     else:
...             d1[k] = d2[k]
...
>>> d1
{'a': 'a1', 'c': 'c2', 'b': ['b1', 'b2']}

Here, the value of the key "b" is an array with the old and the new value.

BTW: has_key() is the old way to check if a dict has a key. The "new" way is to write key in dic, but this is mostly a matter of taste ;)

Regards, mawe

Thanks, mawe! Good stuff.

Thank you much!
I like G-Do's interesting way to create the dictionaries.
I also prefer mawe's second way to merge the dictionaries so nothing gets lost on collision.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.