美文网首页
python 使用zip反转字典

python 使用zip反转字典

作者: 望月成三人 | 来源:发表于2016-12-15 11:43 被阅读1788次

    结合使用zip( )和dict( )可以很方便的反转字典(交换键值对的位置),示例如下:

    >>> d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
    >>> d
    {'a': 1, 'c': 3, 'b': 2, 'd': 4}
    >>> d.keys()
    ['a', 'c', 'b', 'd']
    >>> d.values()
    [1, 3, 2, 4]
    >>> zip(d.values(),d.keys())
    [(1, 'a'), (3, 'c'), (2, 'b'), (4, 'd')]
    >>> dict(zip(d.values(),d.keys()))
    {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
    

    遍历 list,结合zip,dict:

    column_names= ('id', 'name', 'pwd') # key
    rows = [(2, '123', '567')] # vlaue
    
    # 先遍历rows里面的值,然后在用zip反转
    [dict(zip(column_names,row)) for row in rows] if rows else None
    >>>
    [{'name': '123', 'id': 2, 'pwd': '567'}]
    ```

    相关文章

      网友评论

          本文标题: python 使用zip反转字典

          本文链接:https://www.haomeiwen.com/subject/aaowmttx.html