-1

Considering you have a list of dictionaries with different elements e.g:

{
    "acousticness": 0.0681,
    "energy": 0.724,
    "loudness": -5.941,
    "tempo": 132.056,
    "valence": 0.676
},
{
    "acousticness": 0.2754,
    "energy": 0.866,
    "loudness": -7.874,
    "tempo": 180.056,
    "valence": 0.540
},    
{
    "acousticness": 0.0681,
    "energy": 0.724,
    "loudness": -5.941,
    "tempo": 132.056,
    "valence": 0.676
}

And you give the user the ability to enter a dictionary themselves e.g.

{
    "acousticness": 0.1382,
    "energy": 0.7274,
    "loudness": -5.8246,
    "tempo": 122.6412,
    "valence": 0.6153
}

How would you iterate through the dictionary in Python3 to get the closest dictionary back?

I found this explanation on how to find the nearest element in a normal array but can't get around how to do the same with array comparison.

Thanks for any help in advance!

Gabsii
  • 448
  • 7
  • 20

1 Answers1

2

Assuming you want the minimum absolute difference among the values of the dictionaries, you could do something like this:

data = [{
    "acousticness": 0.0681,
    "energy": 0.724,
    "loudness": -5.941,
    "tempo": 132.056,
    "valence": 0.676
},
    {
        "acousticness": 0.2754,
        "energy": 0.866,
        "loudness": -7.874,
        "tempo": 180.056,
        "valence": 0.540
    },
    {
        "acousticness": 0.0681,
        "energy": 0.724,
        "loudness": -5.941,
        "tempo": 132.056,
        "valence": 0.676
    }]

target = {
    "acousticness": 0.1382,
    "energy": 0.7274,
    "loudness": -5.8246,
    "tempo": 122.6412,
    "valence": 0.6153
}


def key(d, t=target):
    return sum(abs(t[k] - v) for k, v in d.items())


result = min(data, key=key)
print(result)

Output

{'tempo': 132.056, 'loudness': -5.941, 'acousticness': 0.0681, 'valence': 0.676, 'energy': 0.724}

The key of the answer, is to use the key parameter of min. Note that this answer can be tweaked to accommodate multiple closeness measures. For example you could change key to compute the euclidean distance between the dictionary values:

import math

def key(d, t=target):
    return math.sqrt(sum((t[k] - v)**2 for k, v in d.items())
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76