python - 如何从列表映射构建字典

标签 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?)来做到这一点?

最佳答案

使用 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'

顺便说一句,除了您自己的映射,您还可以使用 mimetypes :

>>> import mimetypes
>>> mimetypes.guess_type('something.jpg')
('image/jpeg', None)

关于python - 如何从列表映射构建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32085643/

相关文章:

python - Python 2.6 没有模块 'zlib'

python - 根据另一个字典对列表进行排序

python - 通过传递列表来索引字典

C++ 模板与 STL 返回类型相结合

python - urlopen 是否被延迟评估?

python - 有效统计二维数组中每个数的重复次数

Python:这应该是不可能的,不是吗?

python - 稀疏矩阵上的逐元素运算

python - Pandas 按列分组并转换为键 :value pair

c++ - 用于存储大量索引的数据结构,每个索引指向一个集合