0

I want to sort a list according to my specification with a single line of code instead of 2 lines of code, i can assign variable names in a for loop as shown in the sample code but i can't sort using a for loop

my current code works fine but i have to zip 2 lists (new, new2) to finally be able to sort, anyway way to just do it in a single line of code to get 'symbol' and 'priceChange'?

sample = [{'symbol': 'APPL', 'priceChange': '-5.916', 'bidPrice': '0.03201500'}, 
{'symbol': 'URZ', 'priceChange': '2.916', 'bidPrice': '0.03201500'}]


stock = ['APPL']


new = [i['priceChange'] for i in sample if i['symbol'] in stock]
new2 = [i['symbol'] for i in sample if i['symbol'] in stock]

result = list(zip(new2, new))

print(result)

1 Answer 1

3

why not this

new = [[i['priceChange'],i['symbol']] for i in sample if i['symbol'] in stock]
Sign up to request clarification or add additional context in comments.

2 Comments

thank you i tried something similar but didn't add the brackets.
Note that this outputs a list of lists, rather than a list of tuples, which the OP's code outputs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.