简体   繁体   English

如何在Python 2.7中从文件中读取字典?

[英]How to read a dictionary from a file in Python 2.7?

I have a problem with keeping user totals in Python. 我在用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. 我一直在json.dump()信息,并尝试了json.load()但是我无法检索一个特定值,例如是否想知道user2123的余额,而不是每个人。 So basically, I need to know what to call the json.load so I can do nameofdictionary[user2123] and get their balance. 因此,基本上,我需要知道如何调用json.load,以便可以执行nameofdictionary[user2123]并获得它们的平衡。 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}] 该文件如下所示:[{“ 12”:0}] [{“ 123”:0}]

You are not assigning the return-value (a dictionary) of json.load to a variable. 您没有将json.load的返回值(字典) json.load给变量。 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': 或者,如果在选中“ user2123”后不需要词典:

print json.load(open('C:\Users\Joshua\Desktop\Database.txt'))['user2123']

Demo-file Database.txt : 演示文件Database.txt

{"userXYZ":"3.50", "user2123":"42"}

Python-Demo: Python的演示:

>>> 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. 不是有效的JSON。 Valid JSON would look like this: 有效的JSON如下所示:

{"12": 0,"123": 0}

Assuming that's the content of your file: 假设这是文件的内容:

>>> with open('Database.txt') as f:
...     print(json.load(f)['123'])
... 
0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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