Python For循环覆盖字典

时间:2018-08-15 10:43:17

标签: python xml python-3.x python-requests lxml

我有一个for循环,可将订单从请求返回到在线商店。然后将所需的元素插入字典中。我的问题是,当我有一个订单中的多个项目时,它将用请求中的最后一个订单覆盖字典。

使用代码中的print("this is an order"),可以看到订单上有多个项目。

如何增加字典中的索引,以便将其追加到订单项上,而不是覆盖它。

谢谢。

代码:

   #get specifics on each order with orderID from previous request
    tags2 = ('{http://publicapi.ekmpowershop.com/}ProductCode', '{http://publicapi.ekmpowershop.com/}ProductQuantity',
            '{http://publicapi.ekmpowershop.com/}ProductName', '{http://publicapi.ekmpowershop.com/}OrderDate',
            '{http://publicapi.ekmpowershop.com/}ProductPrice')

    for orderItem in xmlFormatter(ekmSingleOrderRequest(str(list(out.values())[0])), "C:/Users/user/Desktop/test2.xml").iter('{http://publicapi.ekmpowershop.com/}OrderItem'):
        out2 = {}
        #here we can the quantity of order items
        print("this is an order item")
        for child in orderItem:
            count = 0
            if child.tag in tags2:
                out2[child.tag[child.tag.index('}')+1:]] = child.text

2 个答案:

答案 0 :(得分:1)

使用列表保存每个项目:

    items = []
    for orderItem in xmlFormatter(ekmSingleOrderRequest(str(list(out.values())[0])), "C:/Users/user/Desktop/test2.xml").iter('{http://publicapi.ekmpowershop.com/}OrderItem'):
        out2 = {}
        #here we can the quantity of order items
        print("this is an order item")
        for child in orderItem:
            if child.tag in tags2:
                out2[child.tag.split('}',1)[1]] = child.text
    items.append(out2)

答案 1 :(得分:0)

使用字典重要吗?您可以改用熊猫数据框吗?

import pandas as pd

df = pd.DataFrame(["A","B"])

for orderItem in xmlFormatter(ekmSingleOrderRequest(str(list(out.values())[0])), "C:/Users/user/Desktop/test2.xml").iter('{http://publicapi.ekmpowershop.com/}OrderItem'):
        out2 = {}
        #here we can the quantity of order items
        print("this is an order item")
        tobeappended = {}
        for child in orderItem:
            count = 0
            if child.tag in tags2:
                tobeappended["A"] = child.tag[child.tag.index('}')+1:]
                tobeappended["B"] = child.text
                df = df.append(tobeappended,ignore_index=True)