简体   繁体   中英

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?

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

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)

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