Andrey Zelentwov
Andrey Zelentwov

Reputation: 13

Transform a list to dict with tuple as key

I want to do from list ['sw0005', 'sw0076', 'Gi1/2', 'sw0005', 'sw0076', 'Gi1/5'] Dict with tuple, which will looks like {('sw0005','sw0076'):'Gi1/2', ('sw0005','sw0076'):'Gi1/5'} How's better it can be done in python?

Upvotes: 0

Views: 47

Answers (2)

I made the iterable more readable

 list1=['sw0005', 'sw0076', 'Gi1/2', 'sw0005', 'sw0076', 'Gi1/5']

 queryable=iter(list1)

 mylist=[]
 for i in range(int(len(list1)/3)):
     mylist.append({(next(queryable),next(queryable)):next(queryable)})

 print(mylist)

Upvotes: 0

tobias_k
tobias_k

Reputation: 82929

You could use an iter of the list to get the next element, and then the next two after that:

>>> lst = ['sw0005', 'sw0076', 'Gi1/2', 'sw0006', 'sw0076', 'Gi1/5']        
>>> it = iter(lst)                                                          
>>> {(a, next(it)): next(it) for a in it}                                   
{('sw0005', 'sw0076'): 'Gi1/2', ('sw0006', 'sw0076'): 'Gi1/5'}

Note: (a) I changes the list so the two tuples are not the same; (b) this will fail if the number of elements is not divisible by three.

As noted in comments, this only works properly a reasonably new version of Python. Alternatively, you can use a range with step and the index:

>>> {(lst[i], lst[i+1]): lst[i+2] for i in range(0, len(lst), 3)}
{('sw0005', 'sw0076'): 'Gi1/2', ('sw0006', 'sw0076'): 'Gi1/5'}

Upvotes: 2

Related Questions