简体   繁体   中英

Get closest dictionary of data with Python

Considering you have a list of dictionaries with different elements eg:

{
    "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 eg

{
    "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!

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())

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM