Skip to content
Advertisement

function that pairs keys of two dictionaries based on how close their values are?

I want to make a function that takes two dictionaries as inputs, where the keys of the dictionaries are strings and the values are ints or floats. It should only use list comprehensions, for-loops, and if statements without imports. for example, an input should look like this:

JavaScript

the goal of this function is to return a single new dictionary comprised of sets of the keys from dictionary 1 and keys from dictionary 2, which are paired based on how close their corresponding values are.

for instance, the input above should return {'person_a': 'place_c', 'person_b': 'place_d'}. this is because the value for 'person_a', 10, in dictionary 1 is closest to the value for 'place_c', 11. The same can be said for the values for 'person_b‘ and 'place_d'. Note that the amount of entires in the new dictionary will always be the amount of entries in dictionary 1, regardless of how many entries are in dictionary 2.

Next, I would like to account for loopholes and exceptions in the function:

for example,

JavaScript

should return

JavaScript

all the values in dictionary 2 are the same, so instead the first key in alphabetical order from dictionary 2 should be paired which each key in dictionary 1 instead.

What I have tried:

the code itself is short and not a function but I wanted to try it as a proof of concept. This method uses a for-loop but I would like to use list comprehension in my function.

JavaScript

the output of this is

JavaScript

as you can see, this does not print the dictionary that I want for my functions output. It does however calculate the distance between each key in dictionary 1 and 2. I wanted to use this to somehow get the minimum values an assemble a dictionary from that.

Advertisement

Answer

Given the question, I would say a simple solution for this would be

JavaScript

I am not entirely sure what you mean by “It should only use list comprehensions and for-loops without imports”. So if we are not allowed to use “if statements”, we can do this using list comprehension

JavaScript

or

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement