简体   繁体   中英

python django dictionaries

I have a list with this format:

[{'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]}]

I want to change its format to:

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

How can I archive this? Please help.

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()]

the rlt is what you want

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]]

Output:

[{'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'}]
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)

output

[{'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]}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM