1

I have a function that generates a report from Excel file. For now, it work like:

import json

def get_dic_from_two_lists(keys, values):
    return { keys[i] : values[i] for i in range(len(keys)) }

def report(items):
    for i in range(items):
        dict_keys = ['name', 'age']
        dict_values = ['n', 'a']
        data = get_dic_from_two_lists(dict_keys, dict_values)
        report = json.dumps(data)
        print(report)
report(5)

Where items is number of reports to generate. It works good, but I need to append results into a list and separate JSON objects with a comma and, moreover, write everything to a file. Any good way to do it? append() function just doesn't seem to work out.

Thanks!

3
  • 1
    Can you fix the indentation and punctuation in your code so that it doesn't produce a syntax error? Commented Jun 27, 2017 at 7:53
  • Sure, already done. Commented Jun 27, 2017 at 7:57
  • post your desired output to be on same page Commented Jun 27, 2017 at 8:53

1 Answer 1

2

You can put all your report objects in the list and then convert it to JSON at once:

import json

def get_dic_from_two_lists(keys, values):
    return { keys[i] : values[i] for i in range(len(keys)) }

def report(items):
    data_list = []
    for i in range(items):
        dict_keys = ['name', 'age']
        dict_values = ['n', 'a']
        data = get_dic_from_two_lists(dict_keys, dict_values)
        data_list.append(data)

    reports = json.dumps(data_list)
    print(reports)

report(5)
Sign up to request clarification or add additional context in comments.

1 Comment

Pure gold, understood my mistake. Thanks!

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.