I have a dictionary comprising of keys and values as integers in a lists, e.g.,
input: {
'example_key1': [358, 57, 18602, 18388],
'example_key2': [415, 12, 4800, 2013],
'example_key3': [450, 10, 4500, 4500],
}
I wish to divide the last value with the second to last value in the list for every key, multiply the answer by 100 and enter the answer into a similar dictionary with with ndigit = 1 point round.
output: {
'example_key1': [98.8], # [round((((18388 / 18602)) * 100), 1)]
'example_key2': [41.9], # [round((((2103 / 4800)) * 100), 1)]
'example_key3': [100.0], # [round((((4500 / 4500)) * 100), 1)]
}
You can use dict-comprehension:
d = {
'example_key1': [358, 57, 18602, 18388],
'example_key2': [415, 12, 4800, 2013],
'example_key3': [450, 10, 4500, 4500]
}
out = {
k: [round((j / i) * 100, 1)]
for k, (*_, i, j) in d.items()
}
print(out)
Prints:
{'example_key1': [98.8], 'example_key2': [41.9], 'example_key3': [100.0]}
Try this (d is your input dict):
res={i:round(d[i][-1]/d[i][-2]*100, 1) if d[i][-2]!=0 else 0.0 for i in d}
print(res)
{'example_key1': 98.8, 'example_key2': 41.9, 'example_key3': 100.0}
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