How to get dictionary from json file in Python?

I got this code to fulfill my needs:

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 get this imprinted:

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 the dictionary to be a string key and get the list as a value. Then iterate over it. How can i do this?

+3
source share
2 answers

json_data is a dictionary. In your first loop, you repeat the list of dictionary keys:

for category in json_data:

will contain key lines - General and Acciones politicas.

You need to replace this loop, which repeats over the letters of the keys:

for trendingtopic in category:

with the following to iterate over the dictionary elements:

for trendingtopic in json_data[category]:
+4
source

I would use a .iteritems()dictionary method that returns key / value pairs:

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

All Articles