Fuzzywuzzy Match with Python Dictionary

Viewed 27

I am trying to compare two dictionaries, find matches, and push the keys from one dictionary, assuming the match ratio is >= 55, to a list.

For example,

foods = {
    "burger": {
        "flavor": ["savory"],
        "vegetarian" : "no",  
        "taste" : ["salty", 'umami'],
    },
    "padthai": {
        "flavor": ["savory", 'nutty'],
        "vegetarian" : "yes",
        "taste" : "salty",
    },
    "cake": {   
        "flavor": "sweet",
        "vegetarian" : "yes",
        "taste" : "tropical",    
    }
}
 
#Define user preference
userPref = {
        "flavor": ["savory","sweet"],
        "vegetarian" : "yes",
        "taste" : ["salty", "tropical"]
}

#Output desired: [cake, ratio score, pad thai, ratio score].

I am using fuzzywuzzy for the score ratio, but am getting this error: AttributeError: 'str' object has no attribute 'values'

I've tried the following ways (with help from other forums), but keep getting this error:

Attempt 1:

def scoreMatch(foods, custDic):
    minMatch = 55
    matchLst = []
    for ele in foods:
        for key, value in ele.items():
            get_value(key, value)
            if(fuzz.token_set_ratio(custDic, value) >= minMatch):
                matchD = {}
                matchD[key] = value
                matchLst.append(matchD)
    print(matchLst)

Attempt 2:

matchLst= [d for d in foods if fuzz.token_set_ratio(userPref, list(d.values())[0]) >= minMatch]

Any help would be huge.

Thank you

1 Answers

In your list comprehension the variable d is the key, which is of type str and has no attribute values. Try foods[d].values() instead, i.e.

matchLst= [d for d in foods if fuzz.token_set_ratio(userPref, list(foods[d].values())[0]) >= minMatch]
Related