Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: merging dictionaries by identical value of key [duplicate]

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!

like image 508
RCN Avatar asked Feb 11 '14 19:02

RCN


1 Answers

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.

like image 176
mgkrebbs Avatar answered Oct 15 '22 04:10

mgkrebbs