python django词典

时间:2017-06-23 06:18:15

标签: python django

我有一个这种格式的列表:

[{'BURGLARY': [0, 1, 1, 0], 'PHYSICAL ASSAULT': [0, 0, 1, 0], 'ROBBERY': 
  [0, 0, 0, 1], 'VANDALISM': [2, 0, 1, 0], 'THEFT': [1, 3, 2, 1], 'DRUGS AND SUBSTANCE ABUSE': [0, 0, 1, 0], 'SEXUAL HARASSMENT': [0, 0, 0, 1]}]

我想将其格式更改为:

[
  {
   name:"BURGLARY",
   data:[0, 1, 1, 0]
  }
   {
   name:"PHYSICAL ASSAULT",
   data:[0, 0, 1, 0]
  }
...
]

我如何存档?请帮忙。

3 个答案:

答案 0 :(得分:3)

data = [{'BURGLARY': [0, 1, 1, 0], 'PHYSICAL ASSAULT': [0, 0, 1, 0], 'ROBBERY': 
      [0, 0, 0, 1], 'VANDALISM': [2, 0, 1, 0], 'THEFT': [1, 3, 2, 1], 'DRUGS 
      AND SUBSTANCE ABUSE': [0, 0, 1, 0], 'SEXUAL HARASSMENT': [0, 0, 0, 1]}]
rlt = [{'name': key, 'data': val} for key,val in data[0].items()]

rlt就是你想要的

答案 1 :(得分:2)

data = [{'BURGLARY': [0, 1, 1, 0], 'PHYSICAL ASSAULT': [0, 0, 1, 0], 'ROBBERY': 
  [0, 0, 0, 1], 'VANDALISM': [2, 0, 1, 0], 'THEFT': [1, 3, 2, 1], 'DRUGS AND SUBSTANCE ABUSE': [0, 0, 1, 0], 'SEXUAL HARASSMENT': [0, 0, 0, 1]}]

new_data = [{ "name": k, "data" : data[0][k]} for k in data[0]]

输出:

[{'data': [0, 0, 0, 1], 'name': 'ROBBERY'},
 {'data': [2, 0, 1, 0], 'name': 'VANDALISM'},
 {'data': [0, 0, 0, 1], 'name': 'SEXUAL HARASSMENT'},
 {'data': [1, 3, 2, 1], 'name': 'THEFT'},
 {'data': [0, 1, 1, 0], 'name': 'BURGLARY'},
 {'data': [0, 0, 1, 0], 'name': 'PHYSICAL ASSAULT'},
 {'data': [0, 0, 1, 0], 'name': 'DRUGS AND SUBSTANCE ABUSE'}]

答案 2 :(得分:1)

a=[{'BURGLARY': [0, 1, 1, 0], 'PHYSICAL ASSAULT': [0, 0, 1, 0], 'ROBBERY': [0, 0, 0, 1], 'VANDALISM': [2, 0, 1, 0], 'THEFT': [1, 3, 2, 1], 'DRUGS AND SUBSTANCE ABUSE': [0, 0, 1, 0], 'SEXUAL HARASSMENT': [0, 0, 0, 1]}]
result=[]
for b in a:
    for i,j in b.items():
        result.append({"name":i,"data":j})
print(result)

输出

[{'name': 'VANDALISM', 'data': [2, 0, 1, 0]}, {'name': 'SEXUAL HARASSMENT', 'data': [0, 0, 0, 1]}, {'name': 'PHYSICAL ASSAULT', 'data': [0, 0, 1, 0]}, {'name': 'DRUGS AND SUBSTANCE ABUSE', 'data': [0, 0, 1, 0]}, {'name': 'THEFT', 'data': [1, 3, 2, 1]}, {'name': 'ROBBERY', 'data': [0, 0, 0, 1]}, {'name': 'BURGLARY', 'data': [0, 1, 1, 0]}]