0

I've created a Python Dictionary Structure as below:

import pprint
log_data = {
    'Date':'',
    'Prayers':{
        'Fajr':'',
        'Dhuhr/Jumu\'ah':'',
        'Asr':'',
        'Maghrib':'',
        'Isha\'a':''
        },
    'Task List':[{
        'Task':'',
        'Timeline':'',
        'Status':''
    }],
    'Meals':{
        'Breakfast':{
            'Menu':'',
            'Place':'',
            'Time':''
        },
        'Lunch':{
            'Menu':'',
            'Place':'',
            'Time':''
        },
        'Evening Snacks':{
            'Menu':'',
            'Place':'',
            'Time':''
        },
        'Dinner':{
            'Menu':'',
            'Place':'',
            'Time':''
        }         
    },
    'Exercises':[{
        'Exercise':'',
        'Duration':''
    }]
} 
pprint.pprint(log_data)

As you see this is just an dictionary structure without data. I want to iterate over all the keys and take input data as value from user using input(). Then I would like to save this dictionary as json file. Could you please help on how I can iterate over all keys and take input from user. Thanks. Searched but couldn't found exact type of help that I need.

1 Answer 1

1

For this kind of thing, one needs to use recursion.

This is not fancy, but will get the job done:

from copy import deepcopy
import json
import pprint


log_data =  {
    'Date':'',
    'Prayers':{
        'Fajr':'',
        'Dhuhr/Jumu\'ah':'',
        'Asr':'',
        'Maghrib':'',
        'Isha\'a':''
        },
    'Task List':[{
        'Task':'',
        'Timeline':'',
        'Status':''
    }],
  # ...
}
def input_fields(substruct, path=""):
    print(f"Inputing values '{path}':")
    for fieldname, value in substruct.items():
        if isinstance(value, (str, int)):
            substruct[fieldname] = input(f"{path}.{fieldname}: ")
        elif isinstance(value, dict):
            input_fields(value, f"{path}.{fieldname}")
        elif isinstance(value, list):
            original = value[0]
            value.pop()
            counter = 0
            if not isinstance(original, dict):
                raise ValueError("Not supported: A list should contain a dictionary-substructure")
            while True:
                item = deepcopy(original)
                input_fields(item, f"{path}.{fieldname}.[{counter}]")
                value.append(item)
                continue_ = input(f"Enter one more {path}.{fieldname} item? (y/n) ").lower().strip()[0] == "y"
                if not continue_:
                    break
                counter+=1
    return substruct

def main():
    values = input_fields(deepcopy(log_data))
    json.dump(values, open("myfile.json", "wt"), indent=4)

if __name__ == "__main__":
    main()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. Works perfectly. @jsbueno

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.