从 python 中的 2 个不同大小的元组创建字典

creating a dictionary from 2 different sized tuples in python

我有 2 个元组需要合并到字典中。 元组 2(值)恰好是元组 1(键)长度的一半

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 )

如何从 python 中的这 2 个元组创建字典(值将在键列表的第二部分重复)?

到目前为止,我的解决方案是像这样将值加倍

validvalues += validvalues
validdict = dict( zip( validexts, validvalues ) )

想知道有没有更pythonic的方法

这里的规范方式是 itertools.cycle:

from itertools import cycle
dict(zip(validexts, cycle(validvalues)))

输出:

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

documentation 中所述,cycle 无限期地重复迭代:

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.

你可以选择

from itertools import chain
validdict = dict( zip( validexts, chain(validvalues, validvalues) ) )

这不会复制 validvalues 元组。