简体   繁体   English

Python:如何为一个键分配多个值

[英]Python: how to assign multiple values to one key

I extract data using API and retrieve a list of servers and backups.我使用 API 提取数据并检索服务器和备份列表。 Some servers have more than one backup.有些服务器有不止一个备份。 This is how I get list of all servers with backaup IDs.这就是我获取具有备份 ID 的所有服务器列表的方式。

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: Json 看起来像这样:

{
   "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.服务器嵌套在storages -> storage中,我需要将几个作为备份 ID 的uuid分配给一个作为服务器 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.我知道collections模块,通过一个简单的例子可以理解,但是我有一个问题,如何在我的例子中使用它来通过 API 提取数据。

How extract origin and assign to this key other values stored in json uuid ?如何提取原点并将存储在 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.您可以存储origin密钥的uuid列表。

I sugget the following 2 ways:我建议以下两种方式:

  1. Creating empty list for first accessing origin , and then appending to it:为首先访问origin创建空list ,然后附加到它:
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:使用defaultdict集合,它在引擎盖下基本上对你做同样的事情:
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 .如果您需要存储uuid唯一列表,您应该使用带有set而不是list的 saem 方法。

A json allows to contain an array in a key: json 允许在键中包含数组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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