Python tuple to dict - ValueError: too many values to unpack

Python tuple to dict - ValueError: too many values to unpack

这是我要转换成字典的元组:

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'}})