I have a list of dictionaries and I would like to extract certain data based on certain conditions. I would like to extract only the currency (as int/float) if the currency is showing USD and more than 0.
curr = [{'currency': '6000.0000,EUR', 'name': 'Bob'},
{'currency': '0.0000,USD', 'name': 'Sara'},
{'currency': '2500.0000,USD', 'name': 'Kenny'},
{'currency': '0.0000,CND', 'name': 'Debbie'},
{'currency': '2800.0000,USD', 'name': 'Michael'},
{'currency': '1800.0000,CND', 'name': 'Aaron'},
{'currency': '2500.0000,EUR', 'name': 'Peter'}]
Results:
usd_curr = [2500.0000, 2800.0000]
This is what I have done.
usd_curr = [line for line in data if ',USD' in line['currency']]
usd_curr = [float(elem['currency'].split(',')[0]) for elem in curr if float(elem['currency'].split(',')[0]) > 0]
The list works but my question is really this - is there a better way to use a variable inside the list comprehension so it will look something like this:
usd_curr = [var = float(elem['currency'].split(',')[0]) for elem in curr if var > 0]
There's no nice syntax to do that using comprehensions. You could use an inner generator to generate the values to cut the repetition, but it'll get unreadable real quick the more complex it gets.
usd_curr = [
float(val)
for val, val_type in (elem['currency'].split(',') for elem in curr)
if val_type == 'USD' and float(val) > 0
]
I'd suggest using a named generator instead.
def get_currency_by_type(curr, curr_type):
for elem in curr:
val, val_type = elem['currency'].split(',')
if val_type == curr_type and float(val) > 0:
yield float(val)
usd_curr = list(get_currency_by_type(curr, 'USD'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With