实际值包含我需要分组的完整列表。 需要拆分为动态组。
它应该拆分为对象数组。
c = {
'Date#1': '07/03/2018',
'Item#1': '789807',
'Description#1': 'Wooden Blocks',
'Qty#1': '4',
'Unit_Price#1': '$10.00',
'Discount#1': '$2.00',
'Total#1': '$38.00',
'Date#2': '07/03/2018',
'Item#2': '789808',
'Description#2': 'Magnetic Alphabets',
'Qty#2': '5',
'Unit_Price#2': '$10.00',
'Discount#2': '$2.00',
'Total#2': '$48.00',
'Date#3': '07/03/2018',
'Item#3': '769804',
'Description#3': 'Building Blocks Flat',
'Qty#3': '3',
'Unit_Price#3': '$23.00',
'Discount#3': '$2.00',
'Total#3': '$67.00'
}
实际值包含我需要分组的完整列表。
需要拆分为动态组。 它应该拆分为对象数组。 我需要的是
c = [{
'Date#1': '07/03/2018',
'Item#1': '789807',
'Description#1': 'Wooden Blocks',
'Qty#1': '4',
'Unit_Price#1': '$10.00',
'Discount#1': '$2.00',
'Total#1': '$38.00'
},
{
'Date#2': '07/03/2018',
'Item#2': '789808',
'Description#2': 'Magnetic Alphabets',
'Qty#2': '5',
'Unit_Price#2': '$10.00',
'Discount#2': '$2.00',
'Total#2': '$48.00'
},
{
'Date#3': '07/03/2018',
'Item#3': '769804',
'Description#3': 'Building Blocks Flat',
'Qty#3': '3',
'Unit_Price#3': '$23.00',
'Discount#3': '$2.00',
'Total#3': '$67.00'
}]
答案 0 :(得分:1)
直到最近,在Python中,dict
个对象都是无序的。要订购字典类型,您需要使用OrderedDict
模块(docs here)中的collections
:
from collections import OrderedDict
from pprint import pprint
c = OrderedDict((
('Date#1', '07/03/2018'),
('Item#1', '789807'),
('Description#1', 'Wooden Blocks'),
('Qty#1', '4'),
('Unit_Price#1', '$10.00'),
('Discount#1', '$2.00'),
('Total#1', '$38.00'),
('Date#2', '07/03/2018'),
('Item#2', '789808'),
('Description#2', 'Magnetic Alphabets'),
('Qty#2', '5'),
('Unit_Price#2', '$10.00'),
('Discount#2', '$2.00'),
('Total#2', '$48.00'),
('Date#3', '07/03/2018'),
('Item#3', '769804'),
('Description#3', 'Building Blocks Flat'),
('Qty#3', '3'),
('Unit_Price#3', '$23.00'),
('Discount#3', '$2.00'),
('Total#3', '$67.00')
))
groups, actual_group = [], OrderedDict()
for k, v in c.items():
if k.startswith('Date'):
if actual_group:
groups.append(actual_group)
actual_group = OrderedDict()
actual_group[k] = v
if actual_group:
groups.append(actual_group)
pprint(groups)
此代码将产生3组OrderedDict
:
[OrderedDict([('Date#1', '07/03/2018'),
('Item#1', '789807'),
('Description#1', 'Wooden Blocks'),
('Qty#1', '4'),
('Unit_Price#1', '$10.00'),
('Discount#1', '$2.00'),
('Total#1', '$38.00')]),
OrderedDict([('Date#2', '07/03/2018'),
('Item#2', '789808'),
('Description#2', 'Magnetic Alphabets'),
('Qty#2', '5'),
('Unit_Price#2', '$10.00'),
('Discount#2', '$2.00'),
('Total#2', '$48.00')]),
OrderedDict([('Date#3', '07/03/2018'),
('Item#3', '769804'),
('Description#3', 'Building Blocks Flat'),
('Qty#3', '3'),
('Unit_Price#3', '$23.00'),
('Discount#3', '$2.00'),
('Total#3', '$67.00')])]