我有一个字符串如下:
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/