gpt4 book ai didi

python - 字符串作为关键字参数,并将来自 str.partition() 输出的多个字典合并为一个字典

转载 作者:太空宇宙 更新时间:2023-11-04 09:42:43 24 4
gpt4 key购买 nike

我有一个字符串如下:

src = "raidlevel=1,slot=0,DISK=1i:1:1_1i:1:2"

我遵循了 here 中的代码示例将其转换为基于分隔符 (=) 的字典。

for i in src.split(','):
key, sep, val = i.partition('=')
dictRaid = {key.lower():val}
if all(k in dictRaid for k in ('raidlevel', 'slot', 'disk')):
print "all arguments present"
print dictRaid

我现在面临的问题是,partition() 函数返回多个单独的字典,因此 if all() 条件返回 False 而不是 True。如何将来自 partition() 函数的这些多个单独的字典结果合并到一个字典中?

最佳答案

dictRaid = {}
src = "raidlevel=1,slot=0,DISK=1i:1:1_1i:1:2"
for i in src.split(','):
key, sep, val = i.partition('=')
dictRaid[key.lower()] = val
if all(k in dictRaid for k in ('raidlevel', 'slot', 'disk')):
print "all arguments present"
print dictRaid

输出:

all arguments present
{'slot': '0', 'raidlevel': '1', 'disk': '1i:1:1_1i:1:2'}
  • 在 for 循环外声明你的字典 dictRaid 并使用 dict.update 添加键值
  • if all(k.. 应该在 for 循环之外。

关于python - 字符串作为关键字参数,并将来自 str.partition() 输出的多个字典合并为一个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51042399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com