Iterate over a dictionary by comprehension and get a dictionary
本问题已经有最佳答案,请猛点这里访问。
如何通过对词典的逐条迭代理解来处理它。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | >>> 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} |
返回结果如下:
1 | set([('.tiff', 'image/tiff'), ('.tif', 'image/tiff')]) |
但是我在等
1 | ('.tif', 'image/tiff') |
如何修改该结果以获得如下字典:
1 | {'.tif': 'image/tiff'} |
替换
1 | {(key,val) for key, val in mime_types.items() if"image/tiff" == val} |
具有
1 | {key: val for key, val in mime_types.items() if"image/tiff" == val} |
表达式:
1 | { value for bar in iterable } |
是一套理解。
为了理解dict,必须为python提供一组由
1 | { key: value for bar in iterable } |
你可以像@anubhav chattoraj建议的那样理解字典。
或将generator expr作为参数传递给函数
1 2 | In [165]: dict((k, mimes[k]) for k in mimes if mimes[k] =="image/tiff") Out[165]: {'.tif': 'image/tiff', '.tiff': 'image/tiff'} |
不要把这两种方法混在一起。
1 2 3 4 5 6 7 8 | you can try something like this >>> print {k : v for k, v in mime_types.iteritems()} Another Simple Example >>> print {i : chr(65+i) for i in range(4)} {0 : 'A', 1 : 'B', 2 : 'C', 3 : 'D'} |