这是我试图转换为字典的元组:
rule_tuple = tuple((('rule1', 'col1', 'val1'), ('rule1', 'col2', 'val2'), ('rule1', 'col3', 'val3'), ('rule2', 'col1', 'val1'), ('rule2', 'col2', 'val2')))
下面是预期的输出:
{'rule1': {'col1': 'val1', 'col2': 'val2', 'col3': 'val3'},
'rule2': {'col1': 'val1', 'col2': 'val2'}}
这是我尝试的:
dict((rule, (dict((c, v) for c, v in (col, val)))) for rule, col, val in rule_tuple)
您可以遍历并将外键的默认值设置为空字典,然后只分配:
rule_tuple = (('rule1', 'col1', 'val1'), ('rule1', 'col2', 'val2'), ('rule1', 'col3', 'val3'), ('rule2', 'col1', 'val1'), ('rule2', 'col2', 'val2'))
d = {}
for k1, k2, v in rule_tuple:
d.setdefault(k1, {})[k2] = v
留给你d
:
{'rule1': {'col1': 'val1', 'col2': 'val2', 'col3': 'val3'},
'rule2': {'col1': 'val1', 'col2': 'val2'}}
在定义rule_tuple
时对tuple()
有冗余调用。修复后:
from collections import defaultdict
result = defaultdict(dict)
rule_tuple = (('rule1', 'col1', 'val1'), ('rule1', 'col2', 'val2'), ('rule1', 'col3', 'val3'), ('rule2', 'col1', 'val1'), ('rule2', 'col2', 'val2'))
for rule, col, val in rule_tuple:
result[rule].update({col:val})
print(result)
输出:
defaultdict(<class 'dict'>, {'rule1': {'col1': 'val1', 'col2': 'val2', 'col3': 'val3'}, 'rule2': {'col1': 'val1', 'col2': 'val2'}})