Basically I want to create a text file (well a few) with key/value pairs that I can then input into Python to create a dictionary with. Then I'm going to call the key and use the resulting value in my equations.
Here's what I want my dictionary to look like when inputted into Python:
usD = {'TWENTYDOLLAR': 2000, 'TENDOLLAR': 1000, 'FIVEDOLLAR': 500, 'DOLLAR': 100, 'QUARTER': 25, 'DIME': 10, 'NICKEL': 5, 'PENNY': 1}
What I'm having an issue with is figuring how how to A) format it in the text file and B) how to properly take the readout from the file and turn it into a dictionary.
twentydollars = change / usD['TWENTYDOLLAR']
change = change % usD['TWENTYDOLLAR']
tendollars = change / usD['TENDOLLAR']
change = change % usD['TENDOLLAR']
Sample of calculations down below to show what type of formatting I need for 开发者_如何转开发the key.
This problem is likely very well suited for json
, pickle
or any other serialization technique. However, if you want to preserve your input as a file consisting of key/value pairs, you could do the following.
File contents (with a delimiter of your choosing, in this case "=", but could be ",", "\t", " ", etc...):
TWENTYDOLLAR=2000
TENDOLLAR=1000
FIVEDOLLAR=500
DOLLAR=100
QUARTER=25
DIME=10
NICKEL=5
PENNY=1
Then, in Python, split each line by the delimiter and build a dict with they key/value pairs (ensuring that the value is an int
):
with open('input.txt', 'r') as inp:
usD=dict(((key, int(value)) for key, value in (line.split('=') for line in inp)))
That's a good use case for the json
module:
>>> import json
>>> usD = {'TWENTYDOLLAR': 2000, 'TENDOLLAR': 1000, 'FIVEDOLLAR': 500,
'DOLLAR': 100, 'QUARTER': 25, 'DIME': 10, 'NICKEL': 5, 'PENNY': 1}
>>> with open("test.json", "w") as out:
... json.dump(usD, out, indent=2)
This creates a file with the following contents:
{
"FIVEDOLLAR": 500,
"TWENTYDOLLAR": 2000,
"PENNY": 1,
"NICKEL": 5,
"DIME": 10,
"TENDOLLAR": 1000,
"QUARTER": 25,
"DOLLAR": 100
}
You can then read that into a new dictionary:
>>> with open("test.json", "r") as inp:
... USD = json.load(inp)
...
>>> USD == usD
True
If you really have to read it from a txt file and you are free to decide the format then use Python itself as a format to keep it simple.
Here's how your input file would look like -
usD = {'TWENTYDOLLAR': 2000,
'TENDOLLAR': 1000,
'FIVEDOLLAR': 500,
'DOLLAR': 100,
'QUARTER': 25,
'DIME': 10,
'NICKEL': 5,
'PENNY': 1
}
Let's call this file curreny.conf
. Then in your python module, you can use execfile()
to execute this file, which will give you usD
dictionary in the scope where you are calling it from.
execfile('path/to/currency.conf')
twentydollars = change / usD['TWENTYDOLLAR']
change = change % usD['TWENTYDOLLAR']
tendollars = change / usD['TENDOLLAR']
change = change % usD['TENDOLLAR']
You can get more details on execfile()
here - http://docs.python.org/library/functions.html#execfile
精彩评论