20

I am new to python and have looked at other answers on merging dictionaries but was still a bit confused. I am looking to merge together two dictionaries in python by a common value within a specific key to output that common key with the other keys from both dictionaries in a new dictionary.

Here is sample data:

add_sal = {'career_medicine': None, 'career_law': None, 'median_salary': None, 'mean_salary': 75000.0, 'career_business': 'operations / logistics', 'number': None}

add_perc = {'percent': 0.07, 'career_business': 'operations / logistics'}

I would like to merge on the key value pair of 'career_business': 'operations / logistics' and output a dictionary that looks like this:

add_all = {'career_medicine': None, 'career_law': None, 'median_salary': None, 'mean_salary': 75000.0, 'career_business': 'operations / logistics', 'number': None, 'percent': 0.07}

An additional problem is that I do not know if the names will match, and I am looping through a list of add_sal and a list of add_perc.

Any advice would be appreciated! Thank you in advance!

4
  • 1
    What if the key exists in both, what do you want to happen then? Commented Feb 11, 2014 at 19:58
  • 1
    In any case, this has been asked many times here on Stack Overflow. I suggest you go through the existing questions to find the one that matches your criteria. Commented Feb 11, 2014 at 19:58
  • 1
    I have created the two dicts such that there is no overlap except for that "career_business" variable.
    – RCN
    Commented Feb 11, 2014 at 19:59
  • 3
    i had looked at that, but I could not tell if they looked at the value of the key. As in, it merges them together but only looking at existence of key. I need the value of the keys to be identical otherwise, would not like it merged.
    – RCN
    Commented Feb 11, 2014 at 20:01

1 Answer 1

9

What you asked for is simply enough done:

import copy
if 'career_business' in add_sal and 'career_business' in add_perc and \
      add_sal['career_business'] == add_perc['career_business']:
   add_all = copy.deepcopy( add_sal )
   add_all['percent'] = add_perc['percent']

However, your data structure seems rather odd for the kind of data you seem to have. You don't say what problem you're trying to solve with it, but your choice of a dictionary with random looking things in it seems likely to be at the root of your problems. Maybe you wanted something more like a dictionary keyed by the career name, like:

career_sal[ 'operations / logistics' ] = 75000.0

and corresponding stuff for the other pieces.

Not the answer you're looking for? Browse other questions tagged or ask your own question.