Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merging two dictionaries of lists with the same keys in python

My problem:

I'm trying to merge two dictionaries of lists into a new dictionary, alternating the elements of the 2 original lists for each key to create the new list for that key.

So for example, if I have two dictionaries:

strings = {'S1' : ["string0", "string1", "string2"], 'S2' : ["string0", "string1"]}

Ns = {'S1' : ["N0", "N1"], 'S2' : ["N0"]}

I want to merge these two dictionaries so that the final dictionary will look like:

strings_and_Ns = {'S1': ["string0", "N0", "string1", "N1", "string2"], 'S2': ["string0", "N0", "string1"]}

or better yet, have the strings from the list joined together for every key, like:

strings_and_Ns = {'S1': ["string0N0string1N1string2"], 'S2': ["string0N0string1"]}

(I'm trying to connect together DNA sequence fragments.)

What I've tried so far:

zip

 for S in Ns:   
     newsequence = [zip(strings[S], Ns[S])]
     newsequence_joined = ''.join(str(newsequence))
     strings_and_Ns[species] = newsequence_joined

This does not join the sequences together into a single string, and the order of the strings are still incorrect.

Using a defaultdict

from collections import defaultdict
strings_and_Ns = defaultdict(list)

    for S in (strings, Ns):
        for key, value in S.iteritems():
        strings_and_Ns[key].append(value)

The order of the strings for this is also incorrect...

Somehow moving along the lists for each key...

for S in strings: 
    list = strings[S]
    L = len(list)
    for i in range(L):
        strings_and_Ns[S] = strings_and_Ns[S] + strings[S][i] + strings[S][i]
like image 274
GGVan Avatar asked Jan 10 '23 15:01

GGVan


1 Answers

strings_and_Ns = {}
for k,v in strings.items():
    pairs = zip(v, Ns[k] + ['']) # add empty to avoid need for zip_longest()
    flat = (item for sub in pairs for item in sub)
    strings_and_Ns[k] = ''.join(flat)

flat is built according to the accepted answer here: Making a flat list out of list of lists in Python

like image 117
John Zwinck Avatar answered Jan 27 '23 15:01

John Zwinck