2017-05-06 66 views
0
attendance = {5: ['Irving', 'Sarah'], 
        1: ['Bill'], 
        2: ['Sarah', 'Fred'], 
        7: ['Paul', 'Alice', 'Irving'], 
        8: ['Bill', 'Fred', 'Sarah'], 
        3: ['Alice', 'Bob'], 
        4: ['David', 'Paul', 'Tom']} 

    for keys, values in attendance.items(): 
     for x in values: 
      print(keys, " : ", len(x)) 

我試圖用len()來計算字典中值的數量,但是我得到的值是錯誤的。
我是新來的Python,所以你可以簡單的解釋一下嗎?謝謝。Python:計數字典中的值

回答

0

通過dict.items()的迭代產生單元單元的元組及其值。看來你正在打印每個字符串的len,而不是列表。你應該這樣做:

In [2]:  attendance = {5: ['Irving', 'Sarah'], 
    ...:     1: ['Bill'], 
    ...:     2: ['Sarah', 'Fred'], 
    ...:     7: ['Paul', 'Alice', 'Irving'], 
    ...:     8: ['Bill', 'Fred', 'Sarah'], 
    ...:     3: ['Alice', 'Bob'], 
    ...:     4: ['David', 'Paul', 'Tom']} 
    ...: 
    ...:  for key, value in attendance.items(): 
    ...:   print(key, " : ", len(value)) 
1 : 1 
2 : 2 
3 : 2 
4 : 3 
5 : 2 
7 : 3 
8 : 3