我有以下字典:
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?)来做到这一点?
答案 0 :(得分:1)
>>> 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)