user3818089
user3818089

Reputation: 345

How to delete a dictionary with JSON in Python 2.7?

I am trying to make a user balances like program that keeps the amount of money they have in a file. I am using JSON to dump the dictionary in the file. I have a problem where I need to delete the previous balance to make room for the new balance without wiping the whole thing. This is what I got so far...

        b = json.load(open('fileplace'))
        newbalance= b[str(account)]-howmuchwd
        b =  b.pop(str(account))
        a= {str(account):newbalance}
        print 'Withdrawal successful!'
        time.sleep(1)
        print 'You have %s dollars left.' %newbalance
        json.dump(b,open('fileplace','a'))
        json.dump(a,open('fileplace','a'))

This cuts out the account number, but not the actual balance. So I need the old info out and the new info in without deleting the all the other balances. I've tried to find answers on google, but nothing has worked thus far. Thanks a bunch!

Upvotes: 0

Views: 101

Answers (2)

snstanton
snstanton

Reputation: 71

Try this:

with open('fileplace') as fp:
   b = json.load(fp)
b[account] -= howmuchwd
with open('fireplace','w') as fp:
   json.dump(b,fp)

This should update the value in place, writing the full dictionary back to the file.

Upvotes: 0

rch
rch

Reputation: 101

When you load the json. It becomes takes the shape of a dictionary. Since you know the key, you can just update the value of the dictionary member.

Upvotes: 1

Related Questions