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

Convert dictionary that has multiple list object into organised tuple format

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

输入格式为

[{'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 替换为 ''