以下是我的字典:
'relay': ['S1=OFF,S2=OFF,S3=OFF,S4=OFF'],
我想要一个o / p :(像嵌套字典一样)
'relay': [['S1':'OFF'],['S2':'OFF'],['S3','OFF'],['S4':'OFF']]
问题在于我无法对密钥和值进行硬编码,它可能会在运行时发生变化。任何人都可以帮我解决这个问题吗?
答案 0 :(得分:2)
可能的方法是:
但是我假设:
的形式
dictified
(缺少更好的名称)的值始终采用['abc=def,abc=...']
d = {'panel': ['STDSWB'], 'relay': ['S1=OFF,S2=OFF,S3=OFF,S4=OFF']}
from collections import defaultdict
def dictionary_maker(d, key):
# Makes new dict to add to previous dictionary
new_dict = defaultdict(dict)
# foreach value in the list
for v in d[key]:
for i in v.split(','):
d_new = i.split('=')
# populate new dict
new_dict[key][d_new[0]] = d_new[1]
# remove old key and add new key
d.pop(key, None)
d[key] = dict(new_dict[key])
return d
d = dictionary_maker(d, 'relay')
print (d)
# d = {'panel': ['STDSWB'], 'relay': {'S1': 'OFF', 'S2': 'OFF', 'S3': 'OFF', 'S4': 'OFF'}}
现在您可以通过执行以下操作来查看“S2”的值:
print (d['relay']['S2']) #OFF
答案 1 :(得分:2)
鉴于字符串是以逗号分隔的键/值列表,其中键和值由等号分隔,您可以使用嵌套字典理解:< / p>
d['relay'] = dict(v.split('=',1) for v in d['relay'][0].split(','))
这会产生:
>>> d = {'panel': ['STDSWB'], 'relay': ['S1=OFF,S2=OFF,S3=OFF,S4=OFF']}
>>> d['relay'] = dict(v.split('=',1) for v in d['relay'][0].split(','))
>>> d
{'relay': {'S2': 'OFF', 'S4': 'OFF', 'S1': 'OFF', 'S3': 'OFF'}, 'panel': ['STDSWB']}