V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
freejewu
V2EX  ›  Python

小白询问,我的程序错误了,请问是为啥?

  •  
  •   freejewu · Oct 31, 2017 · 1973 views
    This topic created in 3101 days ago, the information mentioned may be changed or developed.

    各位大佬询问一下 scores = {} scores[8.45] = 'Joseph' scores[9.12] = 'Zack' scores[7.21] = 'Juan'

    for value in scores.values(): print(scores[value])

    显示 key error ‘ Joseph ’ 这组代码我如果用 for key in scores.keys(): print(scores[key]) 是行得通的。为什么我把方式换成了.values(),就会出错了呢?

    billlee
        1
    billlee  
       Oct 31, 2017   ❤️ 1
    因为字典只能用 key 查 value, 不能用 value 查 key.
    ads1029
        2
    ads1029  
       Nov 1, 2017   ❤️ 1
    你想用 scores[value]来显示什么呢?这样逻辑是不通的
    wangdaqiao
        3
    wangdaqiao  
       Nov 1, 2017
    list(scores.values()), 得到的是 ['Joseph','Zack', 'Juan'] , 而 scores 并没有这几个 key,所以报错。
    其实 scores[value] 这种表达逻辑就是错的,应该用 scores[key]来表示。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1401 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 17:07 · PVG 01:07 · LAX 10:07 · JFK 13:07
    ♥ Do have faith in what you're doing.