I have a requirement where I am getting data from DB in a certain format (List of dictionary), but the next set of methods require data in a certain format (List of tuples). How to convert it.
The input format is
[{'approximate_age_band': ['80-89', '70-79', '60-69'], 'state': ['WY', 'WV', 'WI', 'WA'], 'relationship': ['DEPENDENT', 'SELF', 'SPOUSE'], 'gender': ['Female', 'Male'], 'attribute1_name': ['Medical Plan Type', None], 'attribute1_value': ['POS', None], 'attribute2_name': ['Company Code'], 'attribute2_value': ['M110', None], 'attribute3_name': ['Business Unit', None], 'attribute3_value': ['00001009', '0000444', None], 'attribute4_name': ['Employee Type'], 'attribute4_value': ['Permanent'], 'attribute5_name': [None], 'attribute5_value': [None]}]
The output format which I need from this data is
[('approximate_age_band', '80-89'), ('approximate_age_band', '70-79'), ('approximate_age_band', '60-69'), ('state', 'WY'), ('state', 'WV'), ('state', 'WI'), ('state', 'WA'), ('relationship', 'SPOUSE'), ('relationship', 'SELF'), ('relationship', 'DEPENDENT'), ('gender', 'Male'), ('gender', 'Female'), ('attribute1_name', 'Medical Plan Type'), ('attribute1_value', 'POS'), ('attribute2_name', 'Company Code'), ('attribute2_value', 'M110'), ('attribute3_name', 'Business Unit'), ('attribute3_value', '00001009'), ('attribute3_value', '0000444'), ('attribute4_name', 'Employee Type'), ('attribute5_name', ''), ('attribute5_value', '')]
Can someone please help me with finding the solution.
Advertisement
Answer
You can do it like this:
from itertools import product d = [{'approximate_age_band': ['80-89', '70-79', '60-69'], 'state': ['WY', 'WV', 'WI', 'WA'], 'relationship': ['DEPENDENT', 'SELF', 'SPOUSE'], 'gender': ['Female', 'Male'], 'attribute1_name': ['Medical Plan Type', None], 'attribute1_value': ['POS', None], 'attribute2_name': ['Company Code'], 'attribute2_value': ['M110', None], 'attribute3_name': ['Business Unit', None], 'attribute3_value': ['00001009', '0000444', None], 'attribute4_name': ['Employee Type'], 'attribute4_value': ['Permanent'], 'attribute5_name': [None], 'attribute5_value': [None]}] s = [] for a in d: for i in a: s.extend(list(product([i], filter(None, a[i]))))
gives
[('approximate_age_band', '80-89'), ('approximate_age_band', '70-79'), ('approximate_age_band', '60-69'), ('state', 'WY'), ('state', 'WV'), ('state', 'WI'), ('state', 'WA'), ('relationship', 'DEPENDENT'), ('relationship', 'SELF'), ('relationship', 'SPOUSE'), ('gender', 'Female'), ('gender', 'Male'), ('attribute1_name', 'Medical Plan Type'), ('attribute1_value', 'POS'), ('attribute2_name', 'Company Code'), ('attribute2_value', 'M110'), ('attribute3_name', 'Business Unit'), ('attribute3_value', '00001009'), ('attribute3_value', '0000444'), ('attribute4_name', 'Employee Type'), ('attribute4_value', 'Permanent')]
You should before-hand replace None
by ''
in your input dictionary’s value’s lists.