python - 从嵌套字典中的键获取下一个值
问题描述
我的旧代码以这种形式存储了一个 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)。
解决方案
一个选项可以是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
推荐阅读
- css - 将 flex 对齐到行的底部
- sas - 计数器变量不打算重置
- python - 使用 MDAnalysis 获得径向分布函数
- javascript - Vue 和 Quasar - 模块 '"../../node_modules/vue/types"' 没有导出的成员 'defineComponent'
- matlab - 通过单击点图中的某些点打开子图(MATLAB)
- java - Android View layoutInflater 通过字符串获取布局
- excel - VBA或公式在Excel中分隔街道名称和后缀?
- python - 为什么在 django 中返回 json 响应后值会改变
- python - 我可以在 kivy 2d gui 中预览终端 bash 输出吗
- r - R 对每个事件的每个主题进行最近的观察