【问题标题】:Iterate over a dictionary by comprehension and get a dictionary [duplicate]通过理解迭代字典并获得字典[重复]
【发布时间】:2014-04-10 05:53:05
【问题描述】:

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

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

返回结果如下:

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

但我期待

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

我怎样才能修改该结果以获得像这样的字典:

{'.tif': 'image/tiff'}

【问题讨论】:

    标签: python dictionary dictionary-comprehension


    【解决方案1】:

    您可以按照@Anubhav Chattoraj 的建议执行dictionary comprehension

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

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

    不要将这两种方式混为一谈..

    【讨论】:

    • 如果你避开.items()会更好
    • @thefourtheye 为什么?你不会得到ValueError: too many values to unpack吗?
    • dict((k, mimes[k]) for k in mimes if mimes[k] == image/tiff") 您将避免使用.items() 生成的中间列表
    • @thefourtheye 我现在正在使用 python3...无论如何答案已更新;)
    • 实际上这将在 Python2 和 Python3 中一致地工作。但是,items() 将在 Py3 中返回一个迭代器,但在 Py2 中返回一个列表。
    【解决方案2】:

    表达式:

    { value for bar in iterable }
    

    set comprehension

    为了进行dict理解,你必须为Python提供一组由:分隔的键值对:

    { key: value for bar in iterable }
    

    【讨论】:

      【解决方案3】:
      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'}
      

      【讨论】:

        【解决方案4】:

        替换

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

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

        【讨论】:

        • 以防万一其他人搞砸了,对字典的.items() 调用至关重要。
        猜你喜欢
        • 2016-09-29
        • 2013-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-04
        • 1970-01-01
        相关资源
        最近更新 更多