V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2017-10-31 22:54:21 +08:00 · 1547 次点击
    这是一个创建于 2360 天前的主题,其中的信息可能已经有所发展或是发生改变。

    各位大佬询问一下 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  
       2017-10-31 23:23:35 +08:00   ❤️ 1
    因为字典只能用 key 查 value, 不能用 value 查 key.
    ads1029
        2
    ads1029  
       2017-11-01 00:18:14 +08:00   ❤️ 1
    你想用 scores[value]来显示什么呢?这样逻辑是不通的
    wangdaqiao
        3
    wangdaqiao  
       2017-11-01 12:04:14 +08:00
    list(scores.values()), 得到的是 ['Joseph','Zack', 'Juan'] , 而 scores 并没有这几个 key,所以报错。
    其实 scores[value] 这种表达逻辑就是错的,应该用 scores[key]来表示。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3266 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 12:41 · PVG 20:41 · LAX 05:41 · JFK 08:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.