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 :

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

Leave a Reply