Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to divide dictionary values? [closed]

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)]
}
like image 349
Crimson Avatar asked Mar 09 '26 07:03

Crimson


2 Answers

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]}
like image 182
Andrej Kesely Avatar answered Mar 10 '26 21:03

Andrej Kesely


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}
like image 22
IoaTzimas Avatar answered Mar 10 '26 20:03

IoaTzimas