In [6]: dic={'Customer 1': {'Vitamin A': 0, 'Calcium': 1, 'Protein': 1, 'B vitamins': 0, 'HPMR': 0}, 'Customer 2': {'Vitamin A': 0, 'Calcium': 0, 'Protein': 1, 'B vitamins': 1, 'HPMR': 0}}
In [7]: [tuple([x]+list(y)) for x in dic for y in dic[x].items() ]
Out[7]:
[('Customer 2', 'Calcium', 0),
('Customer 2', 'Vitamin A', 0),
('Customer 2', 'HPMR', 0),
('Customer 2', 'Protein', 1),
('Customer 2', 'B vitamins', 1),
('Customer 1', 'Calcium', 1),
('Customer 1', 'Vitamin A', 0),
('Customer 1', 'HPMR', 0),
('Customer 1', 'Protein', 1),
('Customer 1', 'B vitamins', 0)]
或使用itertools.chain()
:
In [8]: from itertools import chain
In [9]: [tuple(chain(*([x],y))) for x in dic for y in dic[x].items() ]
Out[9]:
[('Customer 2', 'Calcium', 0),
('Customer 2', 'Vitamin A', 0),
('Customer 2', 'HPMR', 0),
('Customer 2', 'Protein', 1),
('Customer 2', 'B vitamins', 1),
('Customer 1', 'Calcium', 1),
('Customer 1', 'Vitamin A', 0),
('Customer 1', 'HPMR', 0),
('Customer 1', 'Protein', 1),
('Customer 1', 'B vitamins', 0)]