将列表对象转换为字典

时间:2018-08-14 19:53:02

标签: python list dictionary

我有一个包含以下项目的列表:

poly = ['AddTicketResponse.xsd',     {
    'OrderServiceType': 'stPickUp',
    'Taxes': {'Tax': {'Caption2': None, 'Caption': 'Sales Tax IN',
              'Amount': '1.26'}},
    'CreditSubtotal': '0',
    'Version': '1',
    'NetSubtotal': '13.97',
    'CreatedTime': '2018-08-14T19:19:13Z',
    'PriceGroupName': '$$Regular Price Group$$',
    'PurchaseSubtotal': '13.97',
    'Status': 'tsOpen',
    'ItemCount': '2',
    'Seq': '105651',
    'Warnings': {'Warning': {'Message': 'The customer name from SpeedLine Connect differs from the name in the customer record.'
                 }},
    'PaymentTotal': '0',
    'Agent': None,
    'ID': '1678'
    'TaxSubtotal': '1.26',
    'MenuSelections': {'MenuSelection': [{
        'MenuCalculatedPriceOfAggregatedSelections': '0',
        'PLU': '44'
        }]}
    }]

此处Poly具有两个对象: 我是Poly [1],它是:

{
    'OrderServiceType': 'stPickUp',
    'Taxes': {'Tax': {'Caption2': None, 'Caption': 'Sales Tax IN',
              'Amount': '1.26'}},
    'CreditSubtotal': '0',
    'Version': '1',
    'NetSubtotal': '13.97',
    'CreatedTime': '2018-08-14T19:19:13Z',
    'PriceGroupName': '$$Regular Price Group$$',
    'PurchaseSubtotal': '13.97',
    'Status': 'tsOpen',
    'ItemCount': '2',
    'Seq': '105651',
    'Warnings': {'Warning': {'Message': 'The customer name from SpeedLine Connect differs from the name in the customer record.'
                 }},
    'PaymentTotal': '0',
    'Agent': None,
    'ID': '1678'
    'TaxSubtotal': '1.26',
    'MenuSelections': {'MenuSelection': [{
        'MenuCalculatedPriceOfAggregatedSelections': '0',
        'PLU': '44'
        }]}
    }

成为一个单独的字典,以便我可以获取“ MenuSelections”的所有值 到目前为止,我只是能够将我的xml文件转换为列表并获得这些值。

root = ElementTree.XML(pos_xml)
xmldict = XmlDictConfig(root)
poly=[]
for key, value in xmldict.iteritems():
    poly.append(value)

老实说,任何建议都会有所帮助。

1 个答案:

答案 0 :(得分:0)

d = poly[1]

这将在poly列表的第二个位置提取对字典的引用,并将其存储为新名称d

然后可以使用它来获取所需的内容

print(d['MenuSelections']['MenuSelection'])

您还可以直接为poly[1]编制索引:

print(poly[1]['MenuSelections']['MenuSelection'][0]['PLU'])

将打印

44