推荐学习书目
› 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 · 2219 views
    This topic created in 3261 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   ·   Privacy   ·   Solana   ·   2410 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 11:25 · PVG 19:25 · LAX 04:25 · JFK 07:25
    ♥ Do have faith in what you're doing.