如何使用python中的一个键添加多个项目?

时间:2019-05-13 09:42:57

标签: python arrays django

如何使用数组中的一个键添加多个键?

def apidurusanalizi_func(self):
    isyerleri = data.iloc[:,0].values
    hatalar = np.delete(data.columns, 0)
    cluster1 = []
             for i,row in  enumerate(bc):
                   for j, y in enumerate(row):
                          if y:
                              isyeri = isyerleri[i]
                              hata = hatalar[j]
                              record = {"isyeri":str(isyeri), hata.lower().replace(" ", ""):hata}
                              if index == 0:
                                 cluster1.append(record)/*add record*/
    return HttpResponse(json.dumps({'cluster1': cluster1}, indent=2), content_type="application/json")

输出如下:

    {
      "cluster1": [
        {
          "isyeri": "15400002",/*the same key*/
          "olcmeodasi": "OLCME ODASI"
        },
        {
          "isyeri": "15400002",/*the same key*/
          "tipdegayari": "TIP DEG AYARI"
        }
    }

我要采用的JSON格式如下:

{
  "cluster1": [
    {
      "isyeri": "15400002", /* the same value for two values */
      "olcmeodasi": "OLCME ODASI"
      "tipdegayari": "TIP DEG AYARI"
    }
}

1 个答案:

答案 0 :(得分:0)

您要创建的集群不是作为字典,而是作为列表:cluster1 = [],然后在其后附加字典:cluster1.append(record)。您应该将cluster1定义为dict并设置记录值。

您的代码不是独立的,不能进行完整的测试,但这应该可以工作:

def apidurusanalizi_func(data):
    isyerleri = data.iloc[:,0].values
    hatalar = np.delete(data.columns, 0)
    cluster1 = {}
    for i,row in  enumerate(bc):
        for j, y in enumerate(row):
            if y:
                isyeri = isyerleri[i]
                hata = hatalar[j]
                if index == 0:
                    cluster1["isyeri"] = str(isyeri)
                    cluster1[hata.lower().replace(" ", "")] = hata
    return HttpResponse(
        json.dumps({'cluster1': cluster1}, indent=2),
        content_type="application/json"
    )