Linked Questions

Popular Questions

Finding multiple minimum in a dictionary of dictionaries

Asked by At

I have a python dict of dicts, and I would like to find all the minimum values for each inner dict, for each key in the outer dict. I will clarify below with an example.

To give a simplified version, say we have this dict of dicts:

my_dict = {'a': {'b': 10, 'c': 5, 'd': 6, 'e': 6, 'f': 6}, 'b': {'a': 10, 'c': 5, 'd': 4, 'e': 4, 'f': 4}, 'c': {'a': 5, 'b': 5, 'd': 7, 'e': 7, 'f': 7}, 'd': {'a': 6, 'b': 4, 'c': 7, 'e': 0, 'f': 0},'e': {'a': 6, 'b': 4, 'c': 7, 'd' : 0, 'f': 0}, 'f': {'a': 6, 'b': 4, 'c': 7, 'd': 0, 'e': 0}}

I want to create a new dict, where for each inner dict, I find the minimum value of that dict and grab the corresponding key value.

So for key a with dict {'b': 10, 'c': 5, 'd': 6, 'e': 6, 'f': 6}, the minimum value is 5, thus I would put a in a new dict assigned to an empty list and then append c to the list since it corresponds with value 5.

The final output for the above list would look like this:

output{a: [c], b: [d, e, f], c: [a, b], d: [e, f], e: [d, f], f: [d, e ]}

The part I am having trouble with is if there are multiple minimum values present. For example, the inner dict for f has two keys (d and e that have value 0, thus both should be returned.

Here is the code I have so far:

new_dict = {}
for k, v in my_dict.items():
    new_dict[k] = [min(v, key=v.get)]

print((new_dict))

Which gives me:

{'a': ['c'], 'b': ['d'], 'c': ['a'], 'd': ['e'], 'e': ['d'], 'f': ['d']}

So it's returning the correct minimum, just not ALL minimums.

Thanks for your time.

Related Questions