Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merging two dictionaries where items are alternated

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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}

recipe:

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()))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading