'Dictionary of lists to list of tuples
t = {"Harvard": [43280, 51143], "Brown": [53419, 62680], "Columbia": [10968, 30257]}
t_pct_change = round((end - start)/start * 100, 2)
list_tuples = [(k, round((t[k][-1] - t[k][0])/t[k][0] * 100, 2)) for k in t for v in t[k]]
The end is the first index of the list and the start is the last index of the list. I want the result to be a list of tuples like
[('Harvard', 18.17), ('Brown', 17.34), ('Columbia', 175.87)]
My code iterates 3 times. How do I fix this or is there a better way to do this?
Solution 1:[1]
You just need to loop once over the dictionary using t.items().
You can also unpack the values so you have nice meaningful names instead of indices.
t = {"Harvard": [43280, 51143], "Brown": [53419, 62680], "Columbia": [10968, 30257]}
my_list = [(uni, round((end - start)/start * 100, 2)) for uni, (start, end) in t.items()]
print(my_list)
Expected output:
[('Harvard', 18.17), ('Brown', 17.34), ('Columbia', 175.87)]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
