Convert a list of tuples of different sizes to a dictionary

I have a list of tuples and you want to turn this list into a dictionary. However, tuples can be larger than 2, and not the same size. I would like the first element of each tuple to be the key, and the rest as an array for the value.

l = [(1,'a','b'),(2,'c'),(3,'d','e','f')] 

Just executing d=dict(l) does not work (in fact, this was not expected). I would like to use the list view along the lines d = dict([(k,v) for k,v in arr]) , but allow v of arbitrary size.

+4
source share
2 answers

Winston Evert has the best (most portable) answer. Alternatively - if you have a recent version of Python - you can use a dictionary understanding:

 d = { t[0]:t[1:] for t in arr } 
+7
source
 d = dict( (v[0], v[1:]) for v in arr ) 
+6
source

Source: https://habr.com/ru/post/1385222/


All Articles