小白问python dict根据value取key值应该怎么写?,pythondict,比如:dicxx = {
小白问python dict根据value取key值应该怎么写?,pythondict,比如:dicxx = {
比如:
dicxx = {'a':'001', 'b':'002'}
需要根据输入001,得到a
如果操作?百度了半天,没找到答案。感谢。
帮你搜索了一下、
>>> dicxx = {'a':'001', 'b':'002'}>>> list(dicxx.keys())[list(dicxx.values()).index("001")]'a'>>>
引用一段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对象总是保持对应关系。
这种情况可以先使用字典推导式反转原字典的key和value,然后就可以根据value选key了。
对于Python3:
dicxx = {'a':'001', 'b':'002'}new_dict = {v:k for k,v in dicxx.items()} # {'001': 'a', '002': 'b'}new_dict['001'] # 'a'
def get_keys(d, value): return [k for k,v in d.items() if v == value] get_keys({'a':'001', 'b':'002'}, '001') # => ['a']
这个情况只能遍历了吧......
dict并不是这样用的啊......
编橙之家文章,
相关内容
- Python requests多线程抓取请求都报异常无解,pythonreques
- Python sys.path哪个命令可以代替append,sys.pathappend,如题。
- python3.x版本 通过urlopen打开一个以html结尾的网址 转换成
- python去重元给中有字典项怎么去重,python字典项,在 p
- Python pip install xlwings遇到error找不到原因,pipxlwings,按照
- 《Python编程实践》for语法使用啥意思,,《Python编程实践
- 准备用python做下载器怎么样?需要了解些知识点,pyt
- python urllib2中打印处理信息的方法是什么,pythonurllib2
- 有Python scrapy下载网站数据的源码可以参考吗,pythonsc
- Python爬虫源码求解析问为何for循环语句无法输出,pyt
评论关闭