2013-10-27 11 views
-1
get_quantities({'t1': ['Vegetarian stew', 'Poutine', 'Vegetarian stew'], 't3': ['Steak pie', 'Poutine', 'Vegetarian stew'], 't4': ['Steak pie', 'Steak pie']}) 

這是我的字典。 t是指表格。返回一個新的詞典與食品的名稱作爲鍵和它的數量作爲值

我需要返回一個新的字典:

{'Vegetarian stew': 3, 'Poutine': 2, 'Steak pie': 3} like this. 

如何我寫這篇文章的代碼?

+1

請在研究中付出努力。嘗試搜索一些關於字典的教程,並嘗試自行完成。如果您嘗試過的代碼有任何問題,請來StackOverflow,我們會幫助您。 – Christian

回答

0
from collections import Counter 

def get_quantities(tables): 
    counter = Counter() 
    for table in tables.iterValues(): 
     counter.update(table) 
    return counter 

這將返回一個Counter,它是一個類似字典的對象。

例如,

quantities = get_quantities({'t1': ['Vegetarian stew', 'Poutine', 'Vegetarian stew'], 't3': ['Steak pie', 'Poutine', 'Vegetarian stew'], 't4': ['Steak pie', 'Steak pie']}) 
print quantities['Vegetarian stew'] 

將打印3

相關問題