How can I find all the differences between the values ​​in the dictionary?

Let's say I have a dictionary:

dictionary = {'A':3,'B',8,'C',12}

      

How could I loop through a dictionary of this type I to find the difference between each value and save the results.

For example, I want (without hardcoding it) to return a dictionary like the following using the dictionary above:

differences = {'A_minus_B':-5,'B_minus_A':5,
               'A_minus_C':-8,'C_minus_A':8,
               'C_minus_B':4,'B_minus_C':-4}

      

I can hardcode it, but I would like my function to be more dynamic, so I can add more elements without having to write tedious lines of code to include a new element.

+3


source to share


3 answers


An efficient but error-free loop solution:



differences = dict()
for k1,v1 in dictionary.items():
    for k2,v2 in dictionary.items():
        if k1==k2: continue
        differences[k1 + '_minus_' + k2] = v1-v2

      

+3


source


You can use itertools.permutations

to create pairs of different vocabulary elements and comprehension vocabulary to create a vocabulary of differences.

from itertools import permutations

diff = {f'{ak} - {bk}': av - bv
        for (ak, av), (bk, bv) in permutations(dictionary.items(), 2)}

print(diff)

      



Outputs

{'A - B': -5, 'A - C': -9, 'B - A': 5, 'B - C': -4, 'C - A': 9, 'C - B': 4}

      

+3


source


How about some understanding of diktat? No import needed and it's relatively readable.

{f'{k1}_minus_{k2}': d[k1] - d[k2] for k1 in d for k2 in d if k1 != k2}

      

(Replace f-string with another form of concatenation if you're not in 3.6)

Output

{'A_minus_B': -5,
 'A_minus_C': -9,
 'B_minus_A': 5,
 'B_minus_C': -4,
 'C_minus_A': 9,
 'C_minus_B': 4}

      

+1


source







All Articles