简体   繁体   English

我需要帮助从Python的嵌入式字典中提取最大值

[英]I need help extracting maximum value from imbedded dictionary in Python

So I have seen a couple of posts on this but they don't line up with my needs because my dict is names, the other posts the keys all have the same string label (key) and I'm not sure how to work around that. 因此,我在此上看到了几篇文章,但它们与我的需求不符,因为我的字典是名称,其他文章的键都具有相同的字符串标签(键),而且我不确定如何解决那。 I have a defaultdict of dicts with the values being their similarity vectors. 我有一个dict的默认字典,值是它们的相似性向量。 so effectively what its doing is the first key is the person to whom all the other keys are comparing and the value is how similar they are. 如此有效地做的第一件事就是与其他所有键都进行比较的人,而值就是它们之间的相似程度。 I want to find the most similar. 我想找到最相似的。

finalDict = defaultdict(dict)

for s in meanDict.keys():
    spk1 = s
    vecSpk1 = meanDict[spk1]
    for t in meanDict.keys():
        if t != spk1:
            spk2 = t
            vecSpk2 = meanDict[spk2]
            sim = Similarity(vecSpk1,vecSpk2)
            finalDict[spk1][spk2] = sim

This is what I have tried so far but i get the error code: TypeError: unhashable type: 'dict' 到目前为止,这是我尝试过的操作,但出现错误代码:TypeError:不能哈希的类型:'dict'

for s in finalDict.keys():
    speaker = finalDict[s]
    max([float(d[speaker]) for d in finalDict.values()]) 

one sample entry looks like this: 一个示例条目如下所示:

defaultdict(<type 'dict'>, {
    'Rand Paul': {
        'Rick Santorum': 0.9915748250754691, 
        'Joseph Biden': 0.9941726131674848, 
        'Lindsey Graham': 0.9976981759787777, 
        'Mike Pence': 0.9898898183716316, 
        'Hillary Clinton': 0.9909482785262219, 
        'John Kasich': 0.9891372990166918, 
        'Barack Obama': 0.9914114570907536, 
        'Marco Rubio': 0.9806612828270346, 
        'Jim Webb': 0.9863228519191483, 
        'Bernie Sanders': 0.9940352419978636, 
        'Ted Cruz': 0.993712852439669, 
        'Lincoln Chafee': 0.9763407586067823
    }
}

To fix your program, you can change the last line to: 要修复程序,您可以将最后一行更改为:

max([d for d in speaker.values()])

However, there are ways to further improve your code. 但是,有一些方法可以进一步改善您的代码。 For instance, consider using the items() method of dicts and the key attribute of the max function: 例如,考虑使用dict的items()方法和max函数的key属性:

for s, speakers in finalDict.items():
    max(speakers.items(), key=lambda x: x[1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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