将具有多个列表对象的字典转换为有组织的元组格式



我有一个要求,即从DB中以特定格式(字典列表(获取数据,但下一组方法需要特定格式(元组列表(的数据。如何转换。

输入格式为

[{'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]}]

我需要这个数据的输出格式是

[('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', '')]

有人能帮我找到解决办法吗。

你可以这样做:

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]))))

给出

[('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')]

您应该先将输入字典的值列表中的None替换为''

最新更新