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

Here's the tuple I'm trying to convert to a dict:

rule_tuple = tuple((('rule1', 'col1', 'val1'), ('rule1', 'col2', 'val2'), ('rule1', 'col3', 'val3'), ('rule2', 'col1', 'val1'), ('rule2', 'col2', 'val2')))

Here's the expected output:

{'rule1': {'col1': 'val1', 'col2': 'val2', 'col3': 'val3'},
 'rule2': {'col1': 'val1', 'col2': 'val2'}}

Here's what I tried:

dict((rule, (dict((c, v) for c, v in (col, val)))) for rule, col, val in rule_tuple)


Solution 1:[1]

You can loop through and set the default value for the outer keys to an empty dict and then just assign:

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

Leaving you with d:

{'rule1': {'col1': 'val1', 'col2': 'val2', 'col3': 'val3'},
 'rule2': {'col1': 'val1', 'col2': 'val2'}}

Solution 2:[2]

You have redundant call to tuple() when defining rule_tuple. After fixing this:

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)

output:

defaultdict(<class 'dict'>, {'rule1': {'col1': 'val1', 'col2': 'val2', 'col3': 'val3'}, 'rule2': {'col1': 'val1', 'col2': 'val2'}})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark
Solution 2