Will91099
Will91099

Reputation: 95

How to return dictionaries from nested loop

I apologize if this is a very basic question, but I built multiple dictionaries using nested loops and I cannot return all the dictionaries, it only returns the first one. I know a part of this is because return is in the wrong indentation, but Python will only allow return data to be indented there. Is there any way to change this function so it returns all the dictionaries?

import urllib.request
import json


def get_url(url):
    text = urllib.request.urlopen(url).read().decode()
    return text


def display_json(text):
    dictionary = json.loads(text)
    for item in dictionary['items']:
        for article in item['articles']:
            line = (article['article'], article['views'])
            data = dict([line])
            return data


def function(data):
    print(data)


def main():
    url = "https://wikimedia.org/api/rest_v1/metrics/pageviews/top/en.wikiversity/all-access/2018/01/all-days"
    text = get_url(url)
    data = display_json(text)
    function(data)


main()

Upvotes: 1

Views: 93

Answers (2)

Bitto
Bitto

Reputation: 8215

Use dictionary comprehension

def display_json(text):
    return {
      item['article']:item['views'] for item in 
      json.loads(text)['items'][0]['articles']
    }

The JSON is structured as follows:

enter image description here

There is no need to loop through items, b'coz it has only one element. We can just get the first element using json.loads(text)['items'][0]. Even if there is more than one item inside items, you can still manage it inside the comprehension.

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 113978

use a generator

def display_json(text):
    dictionary = json.loads(text)
    for item in dictionary['items']:
        for article in item['articles']:
            line = (article['article'], article['views'])
            data = dict([line])
            yield data

data = list(display_json(text))

Upvotes: 1

Related Questions