【问题标题】:Python - dict full of identical valuesPython - 充满相同值的字典
【发布时间】:2013-11-08 18:50:40
【问题描述】:

真的无法摆脱... 这是我的python代码:

 for i in range(len(realjson)) : 
    store["Store"]={
          "id"          :realjson[i]['id'].strip(),
          "retailer_id" :RETAILER_ID,
          "name"        :find(realjson[i]["title"],">","<").strip(),
          "address"     :realjson[i]["address"].strip(),
          "city"        :realjson[i]["address"].split(",")[-4].strip(),
          "province"    :realjson[i]["address"].split(",")[-3].strip(),
          "group"       :realjson[i]["address"].split(",")[-1].strip(),
          "zip"         :realjson[i]["address"].split(",")[-2].strip(),
          "url"         :"http://blabla.com?id="+realjson[i]["id"].strip(),
          "lat"         :realjson[i]["lat"].strip(),
          "lng"         :realjson[i]["lon"].strip(),
          "phone"       :realjson[i]["telephone_number"].replace("<br />Phone Number: ","").strip()
          }

    stores.append(store)
    print stores[i]

当我在 for 循环中打印列表时,它可以正常工作。 否则,当我像这样在循环外打印数组时: print storesit 仅包含我在整个列表长度中重复添加的最后一个元素。 你有什么建议可以帮助我! 谢谢。

【问题讨论】:

    标签: python list dictionary multiple-entries


    【解决方案1】:

    您在循环中重用一个可变对象:

    store['Store']
    

    改为在循环中创建一个新副本:

    newstore = store.copy()
    newstore['Store'] = { ... }
    

    【讨论】:

      【解决方案2】:
      store["Store"]={ ... }
      

      如果您希望这一行只用一个键创建新字典,那么您真正想要的是

      store = {"Store": { ... }}
      

      【讨论】:

        猜你喜欢
        • 2012-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多