Various keys and values, dictionary comprehension

1

I've been playing around with python, dict and list comprehensions. I made this little script:

import requests

url = 'http://www.bankofcanada.ca/en/markets/csv/exchange_eng.csv'
resp = requests.get(url)

page = resp.text

lines = [line for line in page.split('\n') if not line.startswith('#') and line != '' and not line.startswith('Date')]
dictLines = {line.split(', ')[0]: line.split(', ')[1:] for line in lines}

print(dictLines)
print('\n\n\n\n')

results = {i: {'value':dictLines[i][-1] for i in dictLines} for i in dictLines}
print(results)

Output:

{'Singapore dollar': {'value': '0.3653'}, 'Croatian kuna': {'value': '0.3653'}, ...

What I liked, and if possible, is that using this same technique (dict and list understanding). that the output in addition would be:

{'Singapore dollar': {'value': '0.3653', 'code': 'SGD_NOON'}, 'Croatian kuna': {'value': '0.3653', 'code': 'HRK_NOON'}, ...

I tried:

results = {i: {'value':dictLines[i][-1], 'code':dictLines[i][0] for i in dictLines} for i in dictLines}

But unsuccessful

    
asked by anonymous 10.05.2016 / 16:06

2 answers

0

I did, it was a misunderstanding in the syntax:

results = {i: {'code':dictLines[i][0], 'value':dictLines[i][-1]} for i in dictLines}

Output:

{'Romanian new leu': {'value': '0.3287', 'code': 'RON_NOON'}, 'Indonesian rupiah': {'value': '0.000098', 'code': 'IDR_NOON'},...
    
10.05.2016 / 16:33
0
{i: {'values':dictLines[i][-1], 'code':dictLines[i][0]} for i in dictLines}

For a better view, use lib pprint:

>>> import pprint
>>> ret = {i: {'values':dictLines[i][-1], 'code':dictLines[i][0]} for i in dictLines}
>>> pprint.pprint(ret)
{u'Argentine peso': {'code': u'ARS_NOON', 'values': u'0.09108'},
 u'Australian dollar': {'code': u'AUD_NOON', 'values': u'0.9524'},
 u'Bahamian dollar': {'code': u'BSD_NOON', 'values': u'1.2959'},
 u'Brazilian real': {'code': u'BRL_NOON', 'values': u'0.3729'},
...
    
10.05.2016 / 19:02