Assume I’ve got the dictionaries:
dict1 = {'A': 1, 'B': 2, 'C' : 3}
dict2 = {'a': 4, 'b': 5, 'c' : 6}
This link suggest several ways to merge the two but all of the merges are simply concatenations. I want to merge them like a dealer shuffles cards, or like a zipper zips. What I mean by this is that once merging dict1 and dict2, the resulting dict3 should become
dict3 = {'A': 1, 'a': 4, 'B': 2, 'b': 5, 'C' : 3, 'c' : 6}
So the merge grabs elements from dict1 and dict2 in an alternating fashion. My dictionaries are in fact very large so doing it manually is not an option.
>Solution :
There is round-robin itertools recipe to select data this way.
You can use:
dict3 = dict(roundrobin(dict1.items(), dict2.items()))
output:
{'A': 1, 'a': 4, 'B': 2, 'b': 5, 'C': 3, 'c': 6}
from itertools import cycle, islice
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
num_active = len(iterables)
nexts = cycle(iter(it).__next__ for it in iterables)
while num_active:
try:
for next in nexts:
yield next()
except StopIteration:
# Remove the iterator we just exhausted from the cycle.
num_active -= 1
nexts = cycle(islice(nexts, num_active))
You can also use more-itertools.interleave
from more_itertools import interleave
dict(interleave(dict1.items(), dict2.items()))