如何从列表映射构建字典

时间:2015-08-19 02:36:40

标签: python dictionary

我有以下字典:

extension_to_type_mapping = {
 'Metadata': ['xls', 'xml', 'xlsx'],
 'Audio': ['ac3', 'aif', 'aiff', 'flac'],
 'Video': ['avi', 'm2t', 'm2v', 'm4v', 'mov', 'mp4', 'mpg', 'mpeg', 'mxf'],
 'Subtitles/Captions': ['cap', 'cc', 'itt', 'scc', 'srt'],
 'Image': ['jpeg', 'jpg', 'png', 'psd', 'tif', 'tiff', 'ts', 'vob', 'wav'],
 'Other': [None,]
}

我希望能够反转映射,以便我可以调用:

MAPPING['jpg'] ==> 'Metadata'

到目前为止,我有:

MAPPING = {}
for key, list in extension_to_type_mapping.items():
    for i in list:
        MAPPING[i] = key

是否有列表理解或更简单的东西(itertools?)来做到这一点?

4 个答案:

答案 0 :(得分:1)

使用dict comprehension

>>> extension_to_type_mapping = {
...     'Metadata': ['xls', 'xml', 'xlsx'],
...     'Audio': ['ac3', 'aif', 'aiff', 'flac'],
...     'Video': ['avi', 'm2t', 'm2v', 'm4v', 'mov', 'mp4', 'mpg', 'mpeg', 'mxf'],
...     'Subtitles/Captions': ['cap', 'cc', 'itt', 'scc', 'srt'],
...     'Image': ['jpeg', 'jpg', 'png', 'psd', 'tif', 'tiff', 'ts', 'vob', 'wav'],
...     'Other': [None,]
... }
>>> MAPPING = {ext: type_ for type_, exts in extension_to_type_mapping.items()
               for ext in exts}
>>> MAPPING['jpg']
'Image'

BTW,您也可以使用mimetypes

代替自己的映射
>>> import mimetypes
>>> mimetypes.guess_type('something.jpg')
('image/jpeg', None)

答案 1 :(得分:1)

>>> {v:k for k, vs in extension_to_type_mapping.items() for v in vs}

答案 2 :(得分:1)

您可以使用字典理解(从Python 2.7开始) -

MAPPING = {i:key for key,item in extension_to_type_mapping.items() for i in item}

答案 3 :(得分:1)

MAPPING = dict()
for k, v in extension_to_type_mapping.items():
    MAPPING.update((i,k) for i in v)