Skip to content Skip to sidebar Skip to footer

Parsing A Json And Grouping Contents

I have a URL which gives a JSON result. I can parse the json and print the data from the JSON. But my main intention is to group each content and print them into an Excel sheet. Th

Solution 1:

You can use itertools.groupby to group contents using a given key. Have look at How do I use Python's itertools.groupby()? For more information.

In the following I group contents using the category key, which can be anything you want from the dictionary you have as input:

from itertools import groupby


contents = [
    dict(adult=True, id=111, name="Bob"),
    dict(adult=False, id=332, name="Chris"),
    dict(adult=True, id=113, name="John"),
    dict(adult=False, id=224, name="Amir"),
    dict(adult=True, id=115, name="Yann"),
    dict(adult=False, id=336, name="Lee"),
    dict(adult=False, id=227, name="Nadia"),
    dict(adult=False, id=228, name="Lucy")
]

# XXX: make sure to sort the content list# with the key you want to group by
contents.sort(key=lambda content: content['adult'])

# then use groupby with the same key
groups = groupby(contents, lambda content: content['adult'])

for adult, group in groups:
    print'adult', adult
    for content in group:
        print'\t', content

Here is the output:

adult False
    {'id': 332, 'name': 'Chris', 'adult': False}
    {'id': 224, 'name': 'Amir', 'adult': False}
    {'id': 336, 'name': 'Lee', 'adult': False}
    {'id': 227, 'name': 'Nadia', 'adult': False}
    {'id': 228, 'name': 'Lucy', 'adult': False}
adult True
    {'id': 111, 'name': 'Bob', 'adult': True}
    {'id': 113, 'name': 'John', 'adult': True}
    {'id': 115, 'name': 'Yann', 'adult': True}

Post a Comment for "Parsing A Json And Grouping Contents"