简体   繁体   中英

How to read a dictionary from a file in Python 2.7?

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}]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM