2017-04-22 32 views
0

鑑於這種字典格式:Python更新字典,但需要獲得密鑰對?

名稱:(ID,TYPE1,TYPE2,HP,攻擊,防禦,速度,一代傳奇)
字典= { '妙蛙種子':(1, '草',「毒',45,49,49,45,1,假)}

我需要通過數據庫(多個寵物小精靈字典與他們的統計提供的格式),並找到哪個寵物小精靈具有傳奇的地位,這是一個布爾值。我需要計算傳說中的類型並將它們放入新的字典中。

因此,例如,如果Bulbasaur是傳說中的,Grass type = 1 Poison type = 1。新字典項是:

new_dict = {「草」:1,「毒」:1}

我所做的代碼來獲取類型的提取和再算上那些類型是傳奇,但我堅持上如何獲得最終字典的類型和計數。

下面是代碼,我有:

def legendary_count_of_types(db): 

    Fire=0 
    Grass=0 
    Flying=0 
    Poison=0 
    Dragon=0 
    Water=0 
    Fighting=0 
    Ground=0 
    Ghost=0 
    Rock=0 
    Ice=0 
    d={} 
    for key,values in db.items(): 
     status=values[8] 
     if status==True: 
      type_list=get_types(db) 
      for item in type_list: 
       if item=='Fire': 
        Fire+=1 
       if item=='Grass': 
        Grass+=1 
       if item=='Flying': 
        Flying+=1 
       if item=='Poison': 
        Poison+=1 
       if item=='Dragon': 
        Dragon+=1 
       if item=='Water': 
        Water+=1 
       if item=='Fighting': 
        Fighting+=1 
       if item=='Ground': 
        Ground+=1 
       if item=='Ghost': 
        Ghost+=1 
       if item=='Rock': 
        Rock+=1 
       if item=='Ice': 
        Ice+=1 
    d.update() 
    #how do I get the key value pair? 
    return d 

這裏是我的get_types功能的作用:

def get_types(db): 
    l=[] 
    s=[] 
    for key,values in db.items(): 
     types1=str(values[1]) 
     types2-str(values[2]) 
     l.apppend(types1) 
     l.append(types2) 
    for i in l: 
     if i not in s: 
      s.append(i) 
      if 'None' in s: 
       s.remove('None') 
    final_list=s 
    return sorted(final_list) 

回答

1

假設你只想要一個時代的計數類型出現在傳說中的口袋妖怪,而不使用任何像熊貓一樣的花式(你可能應該用你的數據收集,或者可能是一個小的SQL DB)

type_counter = dict() # or use collections.Counter 
for name, attributes in db.items() 
    is_legendary = attributes[8] 
    if is_legendary: 
     type1 = attributes[1] 
     type2 = attributes[2] 
     type_counter[type1] = type_counter.get(type1, 0) + 1 
     type_counter[type2] = type_counter.get(type2, 0) + 1 

# type_counter will now be a dictionary with the counts. 
+0

不幸的是我不允許導入任何模塊。 @nimish –

+1

編輯,計數器只是一個有一些增強的字典。 – nimish

+0

如果沒有列爲類型,則會發生錯誤。 {'Dragon':1,'Fire':4,None:2,'Flying':[37 chars]':1}!= {'Grass':1,'Fire':4,'Flying':2, 'Poiso [41個字符]':1}我怎樣才能過濾'None'類型? –

相關問題