2016-11-15 80 views
-1

我創建了一個函數,用於統計一個國家出現在字典中的次數,並返回出現頻率最高的國家/地區。如果多於一個國家出現的話,那麼它應該返回一個國家名單。無法統計字典中的國家

例詞典:

{'Leonardo da Vinci': [("Portrait of Isabella d'Este", 1499, 63.0, 46.0, 'chalk', 'France'), 
         ('The Last Supper', 1495, 460.0, 880.0, 'tempera', 'Italy')], 
'Pablo Picasso': [('Guernica', 1937, 349.0, 776.0, 'oil paint', 'Spain')]} 

自法國,意大利和西班牙都只能在這本字典中出現一次函數應該返回

countries_appeared_most(dictionary1()) 

['France', 'Italy', 'Spain'] 

如果這些國家的一人,而不是出現2或3次功能將返回該國家。

我現在的代碼下面我認爲是接近解決方案,但我一直得到一個NameError匹配未定義。有誰知道我做錯了什麼?感謝您的幫助

代碼:

def countries_appeared_most(db): 
    matches = {} 
    for painting_list in db.values(): 
     for painting in painting_list: 
      country = painting[-1] 
      matches[country] = matches.get(country, 0) + 1 
      maxcount = max(matches.values()) 
themax = [k for k, count in matches.items() if count == maxcount] 
+1

[爲什麼你問同樣的問題兩次?](http://stackoverflow.com/questions/40599222/python-counting-countries-in-dictionary) –

+0

這是一個不同的問題,我遇到了新問題代碼,所以我問什麼是錯的 – warrior4223

回答

0

首先,看Counter從集合。它已經做了你想做的事情。其次,你的問題是你的縮進。 matches僅在函數的範圍內定義,但最後一行不縮進,因此不被視爲函數的一部分。

+0

謝謝我知道這可能是一些簡單的原因造成的問題 – warrior4223

0

試試這個:

所有的
from collections import Counter 

# unpack the tuples in the dictionary 
countries = [tup[-1] for val in painter_dict.values() for tup in val] 

# create a counter, get the maximum number of appearance 
counter = Counter(countries) 
max_count = max(counter.values()) 

# pull the countries of with values equal to the max_count 
appeared_most = [k for k in counter if counter[k]==max_count] 
+0

感謝您的回答,我得到了我的原代碼工作 – warrior4223