Why am I unable to print JSON attributes in Python? What am I doing wrong?

json, python

Solution

When you iterate over a dictionary, you iterate over its keys. This means that your current code is iterating through the keys of `jobs` (which are strings).

You should use `dict.values` instead:

for val in jobs.values():
    print val["title"]

Now, the code is iterating through the values of `jobs`, which are the dictionaries.

If you want to have the keys and the values, you can use `dict.items`:

for key,val in jobs.items():
    print val["title"]

Problem

I have the following code: ``` 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"] ``` But it won't print out the title each time. I just get `TypeError: string indices must be integers, not str` but if I put `0` instead of `"title"` it just outputs the first character of the number (so all 2s).

Original source