Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

python - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...