通过理解迭代字典并获得字典

Lax*_*khi 11 python dictionary dictionary-comprehension

如何通过字典理解迭代字典来处理它.

>>> mime_types={
    '.xbm': 'image/x-xbitmap',
    '.dwg': 'image/vnd.dwg',
    '.fst': 'image/vnd.fst',
    '.tif': 'image/tiff',
    '.gif': 'image/gif',
    '.ras': 'image/x-cmu-raster',
    '.pic': 'image/x-pict',
    '.fh':  'image/x-freehand',
    '.djvu':'image/vnd.djvu',
    '.ppm': 'image/x-portable-pixmap',
    '.fh4': 'image/x-freehand',
    '.cgm': 'image/cgm',
    '.xwd': 'image/x-xwindowdump',
    '.g3':  'image/g3fax',
    '.png': 'image/png',
    '.npx': 'image/vnd.net-fpx',
    '.rlc': 'image/vnd.fujixerox.edmics-rlc',
    '.svgz':'image/svg+xml',
    '.mmr': 'image/vnd.fujixerox.edmics-mmr',
    '.psd': 'image/vnd.adobe.photoshop',
    '.oti': 'application/vnd.oasis.opendocument.image-template',
    '.tiff':'image/tiff',
    '.wbmp':'image/vnd.wap.wbmp'
}

>>> {(key,val) for key, val in mime_types.items() if "image/tiff" == val}
Run Code Online (Sandbox Code Playgroud)

这是返回结果,如下所示:

set([('.tiff', 'image/tiff'), ('.tif', 'image/tiff')])
Run Code Online (Sandbox Code Playgroud)

但我期待着

('.tif', 'image/tiff')
Run Code Online (Sandbox Code Playgroud)

如何修改该结果以获取如下字典:

{'.tif': 'image/tiff'}
Run Code Online (Sandbox Code Playgroud)

Anu*_*v C 13

更换

{(key,val) for key, val in mime_types.items() if "image/tiff" == val}
Run Code Online (Sandbox Code Playgroud)

{key: val for key, val in mime_types.items() if "image/tiff" == val}
Run Code Online (Sandbox Code Playgroud)

  • 以防万一其他人搞砸了,对字典的“.items()”调用至关重要。 (2认同)

zha*_*hen 5

您可以按照@Anubhav Chattoraj的建议进行字典理解

或者将generator expr作为参数传递给function dict

In [165]: dict((k, mimes[k]) for k in mimes if mimes[k] == "image/tiff")
Out[165]: {'.tif': 'image/tiff', '.tiff': 'image/tiff'}
Run Code Online (Sandbox Code Playgroud)

不要把两种方式混在一起。


Joe*_*ett 5

表达方式:

{ value for bar in iterable }
Run Code Online (Sandbox Code Playgroud)

一套理解力

为了进行dict理解,您必须为Python提供一组键值对,并用:以下分隔:

{ key: value for bar in iterable }
Run Code Online (Sandbox Code Playgroud)