美文网首页
python字典中如何根据value值取对应的key值

python字典中如何根据value值取对应的key值

作者: 码农小杨 | 来源:发表于2017-10-19 11:28 被阅读0次

    代码部分:

    In [26]: a = {1:"a",2:"b"} 
    
    In [27]: a
    Out[27]: {1: 'a', 2: 'b'}
    
    In [28]: list(a.keys())[list(a.values()).index('a')]
    Out[28]: 1
    

    引用一段Python3文档里面的原话。

    If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond.
    

    也就是说,在你迭代的过程中如果没有发生对字典的修改,那么.keys() and .values 这两个函数返回的 dict-view对象总是保持对应关系

    相关文章

      网友评论

          本文标题:python字典中如何根据value值取对应的key值

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