首页 > 解决方案 > 从嵌套字典中的键获取下一个值

问题描述

我的旧代码以这种形式存储了一个 device_name.id 及其分配的 sACN 宇宙:

prev = {
  "312398": 1,
  "232312": 2,
  "312353": 3
}

现在我将它存储为带有附加属性的嵌套字典, device_name.model如下所示:

current = {
  "312341": {
   "model": "Some-Model",
   "universe": 1
  },
  "532342": {
    "model": "Some-other-model",
    "universe": 2
  }
}

我的旧代码有一个功能

def get_free_universe():
        return next(
           i
           for i in range(1, 128)
           if i not in conf.values()
    )

像这样调用:

device_count = sdk.get_device_count() #setup Corsair devices config
for device_index in range(device_count):
    device_name = sdk.get_device_info(device_index)
    device_type = device_name.type
    if device_name.id not in conf:
        if conf.keys == " ":
            print("config empty, universer = 1")
            universe = 1
        else: 
            universe = get_free_universe()
        conf.update({device_name.id: {"model": device_name.model, "universe": universe}}) 
        print(f"conf= {conf}")
    else:
        universe = conf[device_name.id]

现在当然这部分if i not in conf.values()不再起作用了。我需要查看每个 dict 的 key universe。我怎样才能做到这一点?目前,由于字典的device_name.id任何值本身都没有自己的值,所以我无法获得下一个数字,它只是为每个 device_name.id 提供相同的全域(1)。

标签: python

解决方案


一个选项可以是set在新映射中创建所有 Universe 值中的一个。例如,使用上例中的映射:

>>> universes = {v['universe'] for v in current.values()}
>>> universes
{1, 2}

然后,您可以使用新变量universes来代替conf.values()上面所做的。当然,如果您生成并分配一个新的 Universe,您还需要记住将其添加到此哈希集中,如下所示:

>>> universes.add(3)
>>> universes
>>> {1, 2, 3}

get_free_universe然后在函数中需要稍作修改:

def get_free_universe():

    # generate a new universe
    new_universe = next(
        i
        for i in range(1, 128)
        if i not in universes
    )
    
    # add to known universes
    universes.add(new_universe)
    
    return new_universe

推荐阅读