user2005643
user2005643

Reputation:

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

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).

Upvotes: 3

Views: 5563

Answers (2)

user2555451
user2555451

Reputation:

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"]

Upvotes: 3

Mac
Mac

Reputation: 14791

When you use for/in to iterate over a dictionary, it iterates over the dictionary's keys. As such, the iteration variable (job in this case) will contain each of the dictionary's keys in turn: in this case, it'll contain "24", "20", "21", etc.

You want to iterate over the dictionary values (each of the job dictionaries). You can then retrieve the title property of each. To do so, loop like this instead:

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

If you want both the keys and values, you can use iteritems as follows:

for job_key, job in jobs.iteritems():
    print "Job key: ", job_key
    print "Job title: ", job["title"] // or jobs[job_key]["title"]

Note also that jobs is a Python dictionary literal, not JSON (there's actually no JSON involved at all). It's also an illegally formed dictionary literal, since it contains two "24" keys (keys must not be duplicated).

Upvotes: 2

Related Questions