How to use the dictionary function?

This question already has an answer here:

  • Python reverse / invert a mapping 27 answers
  • How do I sort a dictionary by value? 38 answers

  • Yes. You can call items on the dictionary to get a list of pairs of (key, value). Then you can reverse the tuples and pass the new list into dict :

    transposed = dict((value, key) for (key, value) in my_dict.items())
    

    Python 2.7 and 3.x also have dictionary comprehensions, which make it nicer:

    transposed = {value: key for (key, value) in my_dict.items()}
    

    transposed = dict(zip(d.values(), d))
    
    链接地址: http://www.djcxy.com/p/18162.html

    上一篇: 在Python中排序字典

    下一篇: 如何使用字典功能?