I currently have a dictionary
and a list
, and I would like to subtract the list values from the respective dictionary values (based on index position). This is what I have tried so far:
dict1 = {
"appel": 3962.00,
"waspeen": 5018.75,
"ananas": 3488.16
}
number_fruit = [
3962,
5018.74,
3488.17
]
dictionary_values = list(number_fruit)
list_values = list(dict1.values())
are_values_equal = dictionary_values == list_values
But this only returns True
or False
if there is a difference.
But what I want to achieve is to return the difference between number_fruit
list and dict1
dictionary, only if the difference is not equal to zero..
Here is the expected output:
waspeen : 0.01
ananas : -0.01
As mentioned by deceze - dicts do not necessarily have an order, and as such, comparing the values is dangerous.
Here is my attempt at this:
dict1 = {"appel": 3962.00, "waspeen": 5018.75, "ananas": 3488.16}
number_fruit = [3962, 5018.74, 3488.17]
for k, v in dict1.items():
dict_index = list(dict1.keys()).index(k)
if (v - number_fruit[dict_index] != 0):
print(f"{k} : {round(v - number_fruit[dict_index], 2)}")
waspeen : 0.01
ananas : -0.01
Here is a simple solution:
dict1 = {
"appel": 3962.00,
"waspeen": 5018.75,
"ananas": 3488.16
}
number_fruit = [
3962,
5018.74,
3488.17
]
for fruit, a, b in [
(fruit, value, number_fruit[i])
for i, (fruit, value) in enumerate(dict1.items())
]:
print(f'{fruit} : {a} - {b} = {a - b:0.2f}')
Resulting in:
appel : 3962.0 - 3962 = 0.00
waspeen : 5018.75 - 5018.74 = 0.01
ananas : 3488.16 - 3488.17 = -0.01
And it can be even more simple with zip()
:
for ((fruit, a), b) in zip(dict1.items(), number_fruit):
print(f'{fruit} : {a} - {b} = {a - b:0.2f}')
And to have just those items whose differences are not 0
, you can add an if
statement:
for ((fruit, a), b) in zip(dict1.items(), number_fruit):
if (a - b):
print(f'{fruit} : {a} - {b} = {a - b:0.2f}')
Resulting in:
waspeen : 5018.75 - 5018.74 = 0.01
ananas : 3488.16 - 3488.17 = -0.01
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.