4

I got this code for implementing my needing:

import json

json_data = []
with open("trendingtopics.json") as json_file:
    json_data = json.load(json_file)

for category in json_data:
    print category
    for trendingtopic in category:
        print trendingtopic

And this is my json file:

{
    "General": ["EPN","Peña Nieto", "México","PresidenciaMX"],
    "Acciones politicas": ["Reforma Fiscal", "Reforma Energética"]
}

However I'm getting this printed:

Acciones politicas
A
c
c
i
o
n
e
s

p
o
l
i
t
i
c
a
s
General
G
e
n
e
r
a
l

I want to get a dictionary being Strings the keys and got a list as value. Then iterate over it. How can I accomplish it?

1
  • 1
    Did you mean for trendingtopic in json_data[category]: in your inner loop? Commented Feb 6, 2014 at 0:33

2 Answers 2

4

json_data is a dictionary. In your first loop, you're iterating over a list of the dictionary's keys:

for category in json_data:

category will contain key strings - General and Acciones politicas.

You need to replace this loop, which iterates over keys' letters:

for trendingtopic in category:

with the below, so that it iterates over the dictionary elements:

for trendingtopic in json_data[category]:
Sign up to request clarification or add additional context in comments.

1 Comment

ALternatively, you could iterate like this: for key, value in json_data.iteritems(): print key; for item in value: print item
3

I'd use the .iteritems() method of the dictionary which returns key/value pairs:

for category, trending in json_data.iteritems():
    print category
    for topic in trending:
        print topic

4 Comments

Does iteritems implies any higher or lower cost to the operation against simple loop?
I think for ... in mydict: (the 'simple loop') is equivalent to for ... in mydict.iterkeys():. When you use iteritems() I'd guess it's a tiny bit faster because it pulls the key/value pair as a unit, rather than having to go back and lookup whatever value. My motivation is just that it makes the code look a little better.
Great, what happens if my json gets not same structure, for example, somtimes values are lists, sometimes other dictionaries, etc
If trending above was a dictionary rather than a list, it would just print it's keys. If that's what you want, great, but if you need to handle them differently, then you need different code for each.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.