dictionary - Combing two dictionaries with a key and an element in each key (python) -
dictionary - Combing two dictionaries with a key and an element in each key (python) -
i have 2 dictionaries:
let's
maledict = {'jason':[(2014, 394),(2013, 350)...], 'stephanie':[(2014, 3), (2013, 21),..]....} femaledict = {'jason':[(2014, 56),(2013, 23)...], 'stephanie':[(2014, 335), (2013, 217),..]....}
i attempting combine dictionaries thats
completedict = {'jason':[(2014, 394, 56),(2013, 350, 23)...], 'stephanie':[(2014, 3, 335), (2013, 21, 217),..]....}
i not while loops thought seek , utilize list comprehension.
[basedict[x].append((i[0], i[1], j[1])) in maledict[x] j in femaledict[y] if x == y , i[0] == j[0]]
i maintain getting unhashable error. i'm not @ list comprehensions either lol. help appreciated.
python3
for
loops king in python. while
loops have place, objects in python can iterated on using for item in object:
syntax.
here's 1 way it:
from collections import defaultdict maledict = {'jason':[(2014, 394),(2013, 350)], 'stephanie':[(2014, 3), (2013, 21),]} femaledict = {'jason':[(2014, 56),(2013, 23)], 'stephanie':[(2014, 335), (2013, 217),]} name_keys = set(maledict.keys() + femaledict.keys()) combined_names = {} name_key in name_keys: combined_values = defaultdict(list) male_values_dict = dict(maledict[name_key]) female_values_dict = dict(femaledict[name_key]) year_keys = set(male_values_dict.keys() + female_values_dict.keys()) year_key in year_keys: combined_values[year_key].append(male_values_dict[year_key]) combined_values[year_key].append(female_values_dict[year_key]) combined_names[name_key] = dict(combined_values)
output:
{'jason': {2013: [350, 23], 2014: [394, 56]}, 'stephanie': {2013: [21, 217], 2014: [3, 335]}}
or if perfer maintain tuple value:
from collections import defaultdict maledict = {'jason':[(2014, 394),(2013, 350)], 'stephanie':[(2014, 3), (2013, 21),]} femaledict = {'jason':[(2014, 56),(2013, 23)], 'stephanie':[(2014, 335), (2013, 217),]} name_keys = set(maledict.keys() + femaledict.keys()) combined_names = {} name_key in name_keys: combined_values = [] male_values_dict = dict(maledict[name_key]) female_values_dict = dict(femaledict[name_key]) year_keys = set(male_values_dict.keys() + female_values_dict.keys()) year_key in year_keys: tuple_result = (year_key, male_values_dict[year_key], female_values_dict[year_key]) combined_values.append(tuple_result) combined_names[name_key] = combined_values
output:
{'jason': [(2013, 350, 23), (2014, 394, 56)], 'stephanie': [(2013, 21, 217), (2014, 3, 335)]}
note: if in (2014, 394, 56),(2013, 350, 23)
2014 , 2013 keys dictionary improve suited here.
python dictionary append syntax-error python-3.4
Comments
Post a Comment