Home > Blockchain >  Python tuple to dict - ValueError: too many values to unpack
Python tuple to dict - ValueError: too many values to unpack

Time:05-14

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)

CodePudding user response:

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

CodePudding user response:

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