Home > Blockchain >  Extract value by using function with parameter in a dict
Extract value by using function with parameter in a dict

Time:11-05

I have a nested dictionary containing both the title and the number of pages of a book. Here is the dict:

text = {
    1: {
        1: {"ch.name": "The Boy Who Lived", "pages": "146"},
        2: {"ch.name": "The Vanishing Glass", "pages": "126"},
    },
    2: {
        1: {"ch.name": "The Worst Birthday", "pages": "129"},
        2: {"ch.name": "Dobby's Warning", "pages": "125"},
    },
}

And this is my code:

def stranger_binger(seasons,start,pages_left):
    num_pages_watched = 0

    for key1, value1 in seasons.items():
        for key2, value2 in value1.items():
            output = key1,key2,value2['ch.name'],value2['pages']
            output

    for key1, value1 in seasons.items():
        for key2, value2 in value1.items():
            pages_left = pages_left-int(value2['pages'])
            if start == start and pages_left > 0:
                pages_left
            if start == start and pages_left > 0:
                left = pages_left
                print(f"Watched Season {key1} Chapter {key2}: '{value2['ch.name']}', {pages_left} pages left !")
                num_pages_watched = num_pages_watched  1
            elif start == start and pages_left < 0:
                print(f"No more full Chapter today! Only {left} pages are left , but Season {key1} Chapter {key2}: '{value2['ch.name']}' has {value2['pages']}pages.")
                print(f"{num_pages_watched} chapter(s) watched today.")
                return start

stranger_binger({
    1: {
        1: {"ch.name": "The Boy Who Lived", "pages": "146"},
        2: {"ch.name": "The Vanishing Glass", "pages": "126"},
    },
    2: {
        1: {"ch.name": "The Worst Birthday", "pages": "129"},
        2: {"ch.name": "Dobby's Warning", "pages": "125"},
    },
},(1,2),300)

This is the result:

Watched Season 1 Chapter 1: 'The Boy Who Lived', 154 pages left !
Watched Season 1 Chapter 2: 'The Vanishing Glass', 28 pages left !
No more full Chapter today! Only 28 pages are left , but Season 2 Chapter 1: 'The Worst Birthday' has 129pages.
2 chapter(s) watched today.

But I want the result start as 'start' parameter is (1,2) and print:

Watched Season 1 Chapter 2: 'The Vanishing Glass', 174 pages left !
Watched Season 2 Chapter 1: 'The Vanishing Glass', 45 pages left !
No more full Chapter today! Only 45 pages are left , but Season 2 Chapter 2: 'Dobby's Warning' has 125pages.
2 chapter(s) watched today.

CodePudding user response:

You could restructure slightly like this:

def stranger_binger(seasons, start, pages_left):
    num_pages_watched = 0
    started = False # added to determine if we've reached the start point yet
    for season, chapters in seasons.items():
        for chapter, info in chapters.items():
            if not started:
                if start == (season, chapter):
                    started = True
                else:
                    continue # continue to the next chapter until the start point is reached
            pages = int(info['pages'])
            if pages > pages_left:
                print(f"No more full Chapter today! Only {pages_left} pages are left , but Season {season} Chapter {chapter}: '{info['ch.name']}' has {pages} pages.")
                return start
            else:
                pages_left -= pages
                print(f"Watched Season {season} Chapter {chapter}: '{info['ch.name']}', {pages_left} pages left !")
                num_pages_watched = num_pages_watched   1
                

stranger_binger({
    1: {
        1: {"ch.name": "The Boy Who Lived", "pages": "146"},
        2: {"ch.name": "The Vanishing Glass", "pages": "126"},
    },
    2: {
        1: {"ch.name": "The Worst Birthday", "pages": "129"},
        2: {"ch.name": "Dobby's Warning", "pages": "125"},
    },
},(1,2),300)

Descriptive variable names help you piece together the logic better.

I've added a few comments to highlight the important sections.

Output:

Watched Season 1 Chapter 2: 'The Vanishing Glass', 174 pages left !
Watched Season 2 Chapter 1: 'The Worst Birthday', 45 pages left !
No more full Chapter today! Only 45 pages are left , but Season 2 Chapter 2: 'Dobby's Warning' has 125 pages.

It may be helpful to return (season, chapter) so you can start again at the point you left off.

CodePudding user response:

use recursion to find a word phrase in the tree

def find_word(word, json_text):
    for key, value in json_text.items():
        if isinstance(value, dict):
            find_word(word, value)
        else:
            if word in value:
                print(key, value)

find_word("Dobby", json_text)
  • Related