简体   繁体   中英

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)

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)

You could use a dictionary comprehension:

dictionary = {'key' : ('value', 'row_number', 'col_number')}
>>> {k: {'row': row, 'col': col} for k, (_, row, col) in dictionary.items()}
{'key': {'row': 'row_number', 'col': 'col_number'}}

Iterating through dictionary only return nd no need of extra steps for convert list into dictionary. key,

So here we need pair of key and values so we need to use dict.items ,

In [6]: lst = {'a':(0,1),'b':(2,1)}

In [7]: converted_dict = dict((key, dict([('row',value[0]), ('column',value[1])])) for key, value in lst.items())
Out[7]: {'a': {'column': 1, 'row': 0}, 'b': {'column': 1, 'row': 2}}

...and yet another dict-comprehension .

converted_dict = {k : dict(zip(('row', 'column'), v[1:])) for k, v in dictionary.items()}

which for:

dictionary = {'a' : ('value', 1, 2), 'b' : ('value', 0, 0)}

returns:

{'a': {'row': 1, 'column': 2}, 'b': {'row': 0, 'column': 0}}

The only thing wrong with your code is that it is missing the .items() 1 . It had to be:

dict_list = [... for key, value in cleaned_dict]

1. If you are using Python 2 you need .iteritems() instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM