简体   繁体   中英

Python: how to assign multiple values to one key

I extract data using API and retrieve a list of servers and backups. Some servers have more than one backup. This is how I get list of all servers with backaup IDs.

bkplist = requests.get('https://heee.com/1.2/storage/backup')
bkplist_json = bkplist.json()
backup_list = bkplist.json()
backupl = backup_list['storages']['storage']

Json looks like this:

{
   "storages": {
      "storage": [
         {
            "access": "",
            "created": "",
            "license": ,
            "origin": "01165",
            "size": ,
            "state": "",
            "title": "",
            "type": "backup",
            "uuid": "01019",
            "zone": ""
         },

Firstly I create a dictionary to store this data:

backup = {}
for u in backup_list['storages']['storage']:
    srvuuidorg = u['origin']
    backup_uuid = u['uuid']
    backup[srvuuidorg] = backup_uuid

But then I find out there is more than one value for every server. As dictionary can have just one value assigned to one key I wanted to use some hybrid of list and dictionary, but I just can't figure it out how to do this with this example.

Servers are nested in storages -> storage and I need to assign a couple of uuid which is backup ID to one origin which is server ID.

I know about collections module and with a simple example it is quite understandable, but I have a problem how to use this in my example with extracting data through API.

How extract origin and assign to this key other values stored in json uuid ?

What's more it is a massive amount of data so I cannot add every value manually.

You can do something like this.

from collections import defaultdict

backup = defaultdict(list)
for u in backup_list['storages']['storage']: 
    srvuuidorg = u['origin'] 
    backup_uuid = u['uuid'] 
    backup[srvuuidorg].append(backup_uuid)

Note that you can simplify your loop like this.

from collections import defaultdict

backup = defaultdict(list)
for u in backup_list['storages']['storage']:
    backup[u['origin']].append(u['uuid'])

But this may be considering as less readable.

You could store uuid list for origin key.

I sugget the following 2 ways:

  1. Creating empty list for first accessing origin , and then appending to it:
backup = {}
for u in backup_list['storages']['storage']:
    srvuuidorg = u['origin']
    backup_uuid = u['uuid']
    if not backup.get(srvuuidorg):
        backup[srvuuidorg] = []
    backup[srvuuidorg].append(backup_uuid)
  1. Using defaultdict collection, which basically does the same for you under the hood:
from collections import defaultdict


backup = defaultdict(list)
for u in backup_list['storages']['storage']:
    srvuuidorg = u['origin']
    backup_uuid = u['uuid']
    backup[srvuuidorg].append(backup_uuid)

It seems to me that the last way is more elegant. If you need to store uuid unique list you should use the saem approach with set instead of list .

A json allows to contain an array in a key:

var= {
  "array": [
    {"id": 1, "value": "one"},
    {"id": 2, "value": "two"},
    {"id": 3, "value": "three"}
  ]
}

print var
{'array': [{'id': 1, 'value': 'one'}, {'id': 2, 'value': 'two'}, {'id': 3, 'value': 'three'}]}

var["array"].append({"id": 4, "value": "new"})

print var

{'array': [{'id': 1, 'value': 'one'}, {'id': 2, 'value': 'two'}, {'id': 3, 'value': 'three'}, {'id': 4, 'value': 'new'}]}

You can use a list for multiple values.

dict = {"Greetings": ["hello", "hi"]}

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