Reputation: 345
I have a problem with keeping user totals in Python. I've searched and tried many things, but with no success which brings me here. I want to be able to store user totals in a file and retrieve them as needed. I have been json.dump()
the info in and I tried json.load()
but I am not able to retrieve one specific value like if I wanted to know what balance user2123 had, not everyone. So basically, I need to know what to call the json.load so I can do nameofdictionary[user2123]
and get their balance. I don't think my current code would help any, but if you need it, just let me know. Thanks a bunch!
#gets the username
combine=[{str(signup):0}]
json.dump(combine,open('C:\Users\Joshua\Desktop\Balances.txt','a'))
#stuff that doesn't matter
print 'Withdrawing %s dollars... '%howmuchwd
json.load(open('C:\Users\Joshua\Desktop\Database.txt'))
print 'You now have %s dollars' %Idkwhattocallit
The file looks like this: [{"12": 0}][{"123": 0}]
Upvotes: 1
Views: 910
Reputation: 78690
You are not assigning the return-value (a dictionary) of json.load
to a variable. Actually you are not doing anything with the return value :)
You can do
d = json.load(open('C:\Users\Joshua\Desktop\Database.txt'))
print d['user2123']
Or if you don't need the dictionary after checking 'user2123':
print json.load(open('C:\Users\Joshua\Desktop\Database.txt'))['user2123']
Demo-file Database.txt
:
{"userXYZ":"3.50", "user2123":"42"}
Python-Demo:
>>> import json
>>> with open('Database.txt') as f:
... print(json.load(f)['user2123'])
...
42
Edit:
Sorry, I overlooked this issue: The content of your file
[{"12": 0}][{"123": 0}]
is not valid JSON. Valid JSON would look like this:
{"12": 0,"123": 0}
Assuming that's the content of your file:
>>> with open('Database.txt') as f:
... print(json.load(f)['123'])
...
0
Upvotes: 2