Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8537937
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T11:01:16+00:00 2026-06-11T11:01:16+00:00

I create a dictionary and save it to a file using json. The code

  • 0

I create a dictionary and save it to a file using json. The code takes input and updates the dictionary regularly, but unfortunately I can’t get it to write the dictionary properly.
Following is the code that I have written. Have a look in here :

import os, sys, pickle, re, json
from optparse import OptionParser

parser = OptionParser("Store Daily Intakes \n python [Options] <-h help>")
parser.add_option("-n", "--ndays", dest="ndays", action="store", type="int", help="Input the day")
parser.add_option("-m", "--morning", dest="morning", action="store", type="string", help="Input the morning intake format <Banana-1pc,Bread-1pc,CottageChees-2tbs>")
parser.add_option("-l", "--lunch", dest="lunch", action="store", type="string", help="Input the Lunch intake format <Rice-2tbs,Roti-1pc,ChickenCurry-2tbs,Dal-2tbs>")
parser.add_option("-a", "--afternoon", dest="afternoon", action="store", type="string", help="Input the afternoon intake format <Cornflakes-2tbs,Banana-1pc>")
parser.add_option("-d", "--dinner", dest="dinner", action="store", type="string", help="Input the dinner intake format <Pasta-20gms, Cheese-2slice>")

(options, args) = parser.parse_args()

if options.ndays is None or options.morning is None or options.lunch is None or options.afternoon is None or options.dinner is None :
   print parser.print_help()
   exit(-1)


if os.path.isfile("./DailyInTakeFile.json") is True :

    jout = file('./DailyInTakeFile.json','r') # read mode
    CurDct = json.load(jout)
    print CurDct

    DailyInTake = dict()
    DailyInTake["%d" % options.ndays] = {}
    din = DailyInTake["%s" % options.ndays]
    din['Morning'] = options.morning
    din['Lunch'] = options.lunch
    din['Afternoon'] = options.afternoon
    din['Dinner'] = options.dinner

    saved = sys.stdout
    ofile = file('DailyInTakeFile.json', 'a') # append mode

    for idx in CurDct.keys() :
        if int(idx) == options.ndays :
            print idx, options.ndays
            print "The Intake for day # %d exists" %options.ndays
            print "Are you sure you want to overwrite: Type [yes/no]"
            lett=sys.stdin.read()
            if "yes" in lett :
                CurDct[idx]['Morning'] = options.morning
                CurDct[idx]['Lunch'] = options.lunch
                CurDct[idx]['Afternoon'] = options.afternoon
                CurDct[idx]['Dinner'] = options.dinner
                ofile.close()
                sys.exit("Exiting after updating day # %d" % options.ndays)
            else :
                ofile.close()
                sys.exit("Exiting without update")

        else :
            sys.stdout = ofile
            print json.dumps(DailyInTake)
            print ","
            sys.stdout = saved
            ofile.close()

else :
    DailyInTake = dict()
    DailyInTake["%d" % options.ndays] = {}
    din = DailyInTake["%s" % options.ndays]
    din['Morning'] = options.morning
    din['Lunch'] = options.lunch
    din['Afternoon'] = options.afternoon
    din['Dinner'] = options.dinner

   #print DailyInTake

    saved = sys.stdout
    ofile = file('DailyInTakeFile.json', 'a') # append mode
    sys.stdout = ofile
    print json.dumps(DailyInTake)
    print ","
    sys.stdout = saved
    ofile.close()


from datetime import date, timedelta
from subprocess import call
call("cp DailyInTakeFile.json DailyInTakeFile.json.%s" % str(date.today()), shell=True)

The output json file from this code is the following for example :

{"1": {"Lunch": "l3", "Dinner": "d3", "Afternoon": "a3", "Morning": "m3"}}
{"2": {"Lunch": "l3", "Dinner": "d3", "Afternoon": "a3", "Morning": "m3"}}

As you can see it is just adding a single dictionary each time rather than appending to the first one created. I just can’t think it out anymore. Any help will be appreciated.


UPDATE WITH CODE THAT MAINLY CHANGED


 saved = sys.stdout
    for idx in CurDct.keys() :
        if int(idx) == options.ndays :
            print idx, options.ndays
            print "The Intake for day # %d exists" %options.ndays
            print "Are you sure you want to overwrite: Type [yes/no]"
            lett=sys.stdin.read()
            if "yes" in lett :
                ofile = file('DailyInTakeFile.json', 'w') # write mode
                sys.stdout = ofile
                CurDct.update(DailyInTake)
                print json.dumps(CurDct)
                sys.stdout = saved
                ofile.close()
                sys.exit("Exiting after updating day # %d" % options.ndays)
            else :
                sys.exit("Exiting without update")

        else :
            ofile = file('DailyInTakeFile.json', 'w') # write mode
            sys.stdout = ofile
            CurDct.update(DailyInTake)
            print json.dumps(CurDct)
            sys.stdout = saved
            ofile.close()
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T11:01:18+00:00Added an answer on June 11, 2026 at 11:01 am

    According to the code, you create a new dictionary every time. And don’t append to the old one in the file. DailyInTake = dict() So output to the file, just appends a new dictionary.

    My suggestion would be.
    To add the new dictionary index to CurDct as CurDct[index] = DailyInTake[index], then dump the whole dictionary back to the file. You can open the file for writing other than appending.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using the following line of code to create a dictionary which stores
I was using python to create a dictionary but as my data got larger
Alright well I am trying to create a dictionary from a text file so
I'm creating a dictionary database using php and MySQL. The user can search for
I want to create the dictionary of all the ViewModels. public static Dictionary<string, WeakReference>
I'd like to create a Dictionary, the TKey is a string and the TValue
I'm trying to create a dictionary type - ie hash table with a string
I'd like to create a Dictionary that is indexed by Strings: Dictionary(of String, ...)
I am trying to create a dictionary from 2 lists where one list contains
I'm attempting to create a dictionary of hours based off of this calendar: http://disneyworld.disney.go.com/parks/magic-kingdom/calendar/

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.