Search code examples
pythondictionarylist-comprehensionvalueerror

Python create multi-dimensional dictionary using list comprehensions


I have dictionary in the following format:

   dictionary = {'key' : ('value', row_number, col_number)}

I want that dictionary converted to below format:

   converted_dict = {'key' : {'row':row_number, 'col':col_number}}

By using the following code i am getting below error

   dict_list = [(key, dict([('row',value[1]), ('column',value[2])])) for 
                                               key, value in cleaned_dict]
   converted_dict = dict(dict_list)       



   ValueError: too many values to unpack (expected 2)

Solution

  • I don't quite understand why you try to convert the dictionary to list when what you want is in fact dict. It seems you don't understand how to do dict comprehension. Try this approach:

    converted_dict = {
       key: {'row': value[1], 'column': value[2]} for key, value in cleaned_dict.items()
    }
    

    Also note that if you want to iterate over both the keys and the values in a dictionary you should call dictionary.items() (like in the code above)