我有以下代码:
jobs = {"24": {"wage": "empty", "phone": "empty", "title": "sapfh", "description": "sod", "time": "twelve"}, "20": {"wage": "987g", "phone": "iudg", "time": "twelve", "description": "fdgsdfg", "title": "sfgji"}, "21": {"wage": "987g", "phone": "iudg", "title": "sfgji", "description": "fdgsdfg", "time": "twelve"}, "22": {"wage": "987g", "phone": "iudg", "time": "twelve", "description": "fdgsdfg", "title": "sfgji"}, "23": {"wage": "987g", "phone": "iudg", "title": "sfgji", "description": "fdgsdfg", "time": "twelve"}, "24": {"wage": "empty", "phone": "empty", "time": "twelve", "description": "sod", "title": "sapfh"}}
for job in jobs:
print job["title"]
但每次都不会打印出标题。我刚收到TypeError: string indices must be integers, not str
但如果我将0
代替"title"
,则只输出数字的第一个字符(所以全部为2)。
答案 0 :(得分:3)
当您遍历字典时,会迭代其键。这意味着您当前的代码正在遍历jobs
的键(它们是字符串)。
您应该使用dict.values
代替:
for val in jobs.values():
print val["title"]
现在,代码正在迭代jobs
的值,这些是字典。
如果您想拥有密钥和值,可以使用dict.items
:
for key,val in jobs.items():
print val["title"]
答案 1 :(得分:2)
当您使用for
/ in
迭代字典时,它会迭代字典的键。因此,迭代变量(在这种情况下为job
)将依次包含每个字典的键:在这种情况下,它将包含"24"
,"20"
,{{1}等等。
您希望迭代字典值(每个作业字典)。然后,您可以检索每个的"21"
属性。为此,请改为循环:
title
如果您想要键和值,可以使用iteritems,如下所示:
for job in jobs.values():
print job["title"]
另请注意,for job_key, job in jobs.iteritems():
print "Job key: ", job_key
print "Job title: ", job["title"] // or jobs[job_key]["title"]
是Python字典文字,而不是JSON(实际上根本没有涉及JSON)。它也是一个非法形成的字典文字,因为它包含两个jobs
键(键不能重复)。