Multiple keys and values, Dictionary compreension

Asked

Viewed 109 times

1

I have been playing with python, Dict and list compreensions. 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 compreension). that the output beyond that was:

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

I tried to:

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

But to no avail

2 answers

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'},
...

0


I got it, 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'},...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.