Reputation: 15
So, I have a text file which looks like:
AUD_CHF 0.77324
AUD_EUR 0.72657
AUD_GBP 0.61557
AUD_JPY 86.88
AUD_USD 0.76835
CAD_EUR 0.722459831
CAD_GBP 0.612726326
CAD_CHF 0.76915
CHF_EUR 0.939858457
CHF_GBP 0.795924865
What I want to do is read through it and put each currency into it's own dictionary eg.
AUD {AUD_CHF: 0.77324, AUD_EUR :0.72657 AUD_GBP :0.61557 AUD_JPY :6.88, AUD_USD :0.76835}
then CHF, USD etc. There will be 18 dictionaries when finished. I've managed to do this with the folowing code (with some help on another question) but it is long and not very pythonic as I understand it. It looks like this
USD = {}
AUD = {}
CHF = {}
with open('rates.txt', 'r') as f:
for line in f:
split_line = line.split()
if line.startswith('USD'):
USD[split_line[0]] = split_line[1]
elif line.startswith('AUD'):
AUD[split_line[0]] = split_line[1]
elif line.startswith('CHF'):
CHF[split_line[0]] = split_line[1]
I mean, it works but I can't imagaine there isn't a better way. I spoke to a friend and he suggested a solution, it used vars(), local() and from what I read that's not a great thing and I couldn't get it to work the way I wanted. I was thinking a loop of some kind but I can't get anything going. If anyone has any ideas for me to try I would be grateful. Even if it only a skeleton so I can go and try to make it work.
Thanks for your time, apologies this is a bit long.
Upvotes: 1
Views: 51
Reputation: 5805
How about a dictionary of dictionaries and some defaultdict:
from collections import defaultdict
currencies = defaultdict(dict)
with open('rates.txt', 'r') as f:
for line in f:
if line:
currency, rate = line.split()
currencies[currency[:3]][currency] = rate
Resulting in:
In [39]: currencies['AUD']
Out[39]:
{'AUD_CHF': '0.77324',
'AUD_EUR': '0.72657',
'AUD_GBP': '0.61557',
'AUD_JPY': '86.88',
'AUD_USD': '0.76835'}
In [40]: currencies['CHF']
Out[40]: {'CHF_EUR': '0.939858457', 'CHF_GBP': '0.795924865'}
In [41]: currencies['CAD']
Out[41]: {'CAD_CHF': '0.76915', 'CAD_EUR': '0.722459831', 'CAD_GBP': '0.612726326'}
Edit.
If you have lines that do not comply with space separation, you can try a try/except block amongst other things:
from collections import defaultdict
currencies = defaultdict(dict)
with open('rates.txt', 'r') as f:
for line in f:
if line:
try:
currency, rate = line.split()
except ValueError:
# good practice to log here, if you were to have logging.
continue #skip to next line
currencies[currency[:3]][currency] = rate
Upvotes: 1