I have 2 tuples which I need to combine into a dictionary. tuple 2 ( the values ) is exactly half the length of tuple 1 ( the keys )
validexts = (
'.pz3','.cr2','.pz2','.pp2','.hr2','.fc2','.hd2','.lt2','.cm2','.mt5','.mc6',
'.pzz','.crz','.p2z','.ppz','.hrz','.fcz','.hdz','.ltz','.cmz','.mz5','.mcz' )
validvalues = (
'scene','character','pose','props','hair','face','hand','light',
'camera','materials','materials )
how can I make a dictionary ( the values will be repeated for the second part of the key list ) from these 2 tuples in python ?
so far my solution has been to double the values like this
validvalues = validvalues
validdict = dict( zip( validexts, validvalues ) )
I would like to know if there is a more pythonic way.
CodePudding user response:
The canonical way here would be itertools.cycle
:
from itertools import cycle
dict(zip(validexts, cycle(validvalues)))
Output:
{'.pz3': 'scene',
'.cr2': 'character',
'.pz2': 'pose',
'.pp2': 'props',
'.hr2': 'hair',
'.fc2': 'face',
'.hd2': 'hand',
'.lt2': 'light',
'.cm2': 'camera',
'.mt5': 'materials',
'.mc6': 'materials',
'.pzz': 'scene',
'.crz': 'character',
'.p2z': 'pose',
'.ppz': 'props',
'.hrz': 'hair',
'.fcz': 'face',
'.hdz': 'hand',
'.ltz': 'light',
'.cmz': 'camera',
'.mz5': 'materials',
'.mcz': 'materials'}
As mentioned in the documentation, cycle
repeats the iterable indefinitely:
Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely.
CodePudding user response:
You can go with
from itertools import chain
validdict = dict( zip( validexts, chain(validvalues, validvalues) ) )
This will not copy the validvalues
tuple.