Home > Net >  Creating a new dict by merging two dictionaries retaining key value pairs
Creating a new dict by merging two dictionaries retaining key value pairs

Time:02-03

I am trying to create a new dictionary with updated keys and values from two dicts.

I have two dictionaries:

r = {'seq1': 'cgatcgatacgatgcgatgctagatcgagtgcatcgcggcgccgcgcgcgcatgcagcagctacgatgcattaatccgatcgatcgagtacgatata', 'seq2':'cgatcgatacgatgcgatgctagatcgagtgcatcgcggcgccgcgcgcgcatgcagcagctacgatgcattaatccgatcgatcgagt', 'seq3':'cgatcgatacgatgcgatgctagatcgagtgcatcgcggcgccgcgcgcgcatgcagcagctacgatgcattaatccgatcgatcgagtacgatatataatatacgatcagctagcc'}

pr = {'seq1': [(124, 22), (114, 22)],
 'seq2': [(100, 22)],
 'seq3': [(124, 22)]}

This is my current code:

for key, val in r.items():
    for val2 in pr.values():
        print({'name': key, 'size': len(val), 'p_list' : val2})

With an output like this:

{'name': 'seq1', 'size': 163, 'p_list': [(124, 22), (114, 22)]}
{'name': 'seq1', 'size': 163, 'p_list': [(100, 22)]}
{'name': 'seq1', 'size': 163, 'p_list': [(124, 22)]}
{'name': 'seq2', 'size': 163, 'p_list': [(124, 22), (114, 22)]}
{'name': 'seq2', 'size': 163, 'p_list': [(100, 22)]}
{'name': 'seq2', 'size': 163, 'p_list': [(124, 22)]}
{'name': 'seq3', 'size': 215, 'p_list': [(124, 22), (114, 22)]}
{'name': 'seq3', 'size': 215, 'p_list': [(100, 22)]}
{'name': 'seq3', 'size': 215, 'p_list': [(124, 22)]}

I want the output to look like this:

{'name': 'seq1', 'size': 163, 'p_list': [(124, 22), (114, 22)]}
{'name': 'seq2', 'size': 163, 'p_list': [(100, 22)]}
{'name': 'seq3', 'size': 163, 'p_list': [(124, 22)]}

I assume the issue is due to my nested for loop, but no matter the permutation I can't seem to get this to work. I've also tried using the .update() method, but that hasn't worked for me either. Any advice is appreciated!

CodePudding user response:

You can use a list comprehension with zip to group corresponding elements.

res = [{'name': key, 'size': len(val), 'p_list': val2} for (key, val), val2 
           in zip(r.items(), pr.values())]

If the key is the same between both dicts, then you only need to loop over the items of one dict.

res = [{'name': key, 'size': len(val), 'p_list': pr[key]} for key, val in r.items()]

CodePudding user response:

You can use a dictionary comprehension to achieve the desired output:

result = [{'name': key, 'size': len(r[key]), 'p_list': pr[key]} for key in r.keys() & pr.keys()]

The r.keys() & pr.keys() line ensures that you only include keys that are present in both dictionaries, otherwise you might get a KeyError.

CodePudding user response:

If you know the key will always be the same for the two dictionaries, you can just iterate over one of the dictionaries and then use the key to access the 2nd dictionary's value.

for key, val in r.items():
    print({'name': key, 'size': len(val), 'p_list' : pr[key]})
  • Related