【发布时间】:2018-06-29 15:04:55
【问题描述】:
我是 Python 新手,仍在学习如何使用。我有以下字典:
dic = {'0': {'text': 'a', 'lang': 'es', 'rating': '4'}, '1': {'text': 'b', 'lang': 'es', 'rating': '3'}, '2': {'text': 'c', 'lang': 'es', 'rating': '1'}, '3': {'text': 'd', 'lang': 'es', 'rating': '2'}, '4': {'text': 'e', 'lang': 'es', 'rating': '5'}}
现在,我想知道文本,例如“a”是否是任何嵌套字典的值(我知道有一个 value() 函数返回字典的值,但是在这种情况下它只会返回第一个字典的值,不是吗?像 0,1,2,3,4)
我试过了
for i in range(len(dic)):
if text in dic[i].values():
print("Yes")
else:
print("No")
但这给了我一个值为“0”的 KeyError。我搜索了类似的问题,但没有找到任何可以用来解决我的问题的问题。你能帮我么?提前致谢。
【问题讨论】:
-
for i in range(len(dic))将遍历整数,直到字典中的键数,这在此处可能有效。但是,您真正想要的是for k in dic,它将遍历键。
标签: python python-3.x dictionary