在Python中打印字典值 [英] Printing dictionary values in Python

查看:473
本文介绍了在Python中打印字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本这样的字典:

a={'*Initial*': {'H': 0.8, 'C': 0.2}, 'C': {'H': 0.4, 'C': 0.6}, 'H': {'H': 0.7, 'C': 0.3}}

当我尝试打印以下内容时:

When I try to print the following:

print {k:v[0] for (k,v) in a.items()}

我得到一个错误:

File "...", line 3, in <module>
    print {k:v[0] for (k,v) in a.items()}
  File "...", line 3, in <dictcomp>
    print {k:v[0] for (k,v) in a.items()}
KeyError: 0

有人可以解释为什么会这样吗?

Can someone please explain why this is happening?

推荐答案

在您的字典中,"v"是"k"的值,但是"v"也是另一个字典,因此您无法通过这样做来为其编制索引v [0],您需要给它一个有效的密钥,例如

In your dictionary, "v" is the value of "k", but "v" is also another dictionary, so you are unable to index it by doing v[0], instead you need to give it a valid key like

print {k:v['H'] for (k,v) in a.items()}

这将打印出值0.8、0.4和0.7.

which would print out the values 0.8, 0.4 and 0.7.

这篇关于在Python中打印字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆