Iterating through a dictionary by understanding and getting a dictionary

How to iterate over a dictionary according to the concept of a dictionary for its processing.

>>> 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} 

This returns the result as follows:

 set([('.tiff', 'image/tiff'), ('.tif', 'image/tiff')]) 

But I expect

 ('.tif', 'image/tiff') 

How can I change this result to get a dictionary like:

 {'.tif': 'image/tiff'} 
+7
python dictionary dictionary-comprehension
source share
4 answers

Expression:

 { value for bar in iterable } 

is an established understanding .

To complete the dict understanding, you must provide Python with a set of key-value pairs separated by a character::

 { key: value for bar in iterable } 
+2
source share

Replace

 {(key,val) for key, val in mime_types.items() if "image/tiff" == val} 

from

 {key: val for key, val in mime_types.items() if "image/tiff" == val} 
+12
source share

You can make an understanding of the dictionary , as @ Anubhav Chattoraj suggested.

Or pass the expr generator as an argument to the dict function:

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

Do not mix two paths up.

+3
source share
 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'} 
+1
source share

All Articles