【问题标题】:Python For loop Overwriting dictPython For循环覆盖字典
【发布时间】:2018-08-15 10:43:16
【问题描述】:

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

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

如何增加 dict 中的索引,以便将订单项附加到它而不是覆盖它。

提前致谢。

代码:

   #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

【问题讨论】:

  • 将订单放入列表中。

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


【解决方案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)

【讨论】:

  • 干杯,我知道我错过了一些简单的东西!
【解决方案2】:

使用字典重要吗?你可以改用 pandas 数据框吗?

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)

【讨论】:

  • Dataframe-Indices 不应是 AB,而是 OP 正在使用的标签。
  • 在这里使用pandas 有什么好处?
猜你喜欢
  • 2019-02-13
  • 2016-07-17
  • 1970-01-01
  • 1970-01-01
  • 2017-12-25
  • 2018-06-01
  • 1970-01-01
  • 2017-07-21
  • 1970-01-01
相关资源
最近更新 更多