Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge the list in `defaultdict` using keys, but keep the list separate within that key?

Tags:

I want to merge the list in defaultdict which has class (keys) and list-values from two different data/file. I want to merge the list using the unique key but keep the list values separate.

Input:

defaultdict(<class 'list'>, {'1335': ['C', 'T', 'T', 'C', 'T', 'G'], '254': ['T', 'T', 'G', 'C', 'G', 'G']})

defaultdict(<class 'list'>, {'1335': ['A', 'C', 'A', 'A', 'C', 'A'], '254': ['A', 'G', 'A', 'T', 'A', 'A']})

output:

defaultdict(<class 'list'>, {'1335': ['C', 'T', 'T', 'C', 'T', 'G'], ['A', 'C', 'A', 'A', 'C', 'A'] , '254': ['T', 'T', 'G', 'C', 'G', 'G'], ['A', 'G', 'A', 'T', 'A', 'A']})

Thanks,

like image 392
everestial007 Avatar asked Jan 28 '17 16:01

everestial007


1 Answers

You want the new dictionary's value to be a list of lists.

You can create a new defaultdict of lists, and append the list value from each dictionary:

input_dicts = [dict1, dict2]

result = defaultdict(list)

for to_merge in input_dicts:
    for key, value in to_merge.items():
        result[key].append(value)
like image 59
Peter Wood Avatar answered Sep 25 '22 10:09

Peter Wood