2016-04-26 73 views
0

我有以下代碼來打印字典中的項目。dict.items()在python字典返回類型

my_dict = { 
       "apples": 430, 
       "bananas": 312, 
       "oranges": 525, 
       "pears": 217, 
       "strawberries": 267, 
       "blueberry": 179, 
       "boysenberry": 432, 
       "blackberry": 266, 
       "apricot": 321, 
       "plum": 143, 
       "peaches": 154 
      } 

for k, v in my_dict.items(): 
    print('key {} value {}\n'.format(k, v)) 

上面的代碼工作正常,並打印鍵和值。只是出於好奇,我想嘗試

k,v = my_dict.items() 

它給了我一個錯誤。我想知道這是爲什麼?我的理解是,my_dict.items()返回k and v

+2

'.items()'給你鍵值對的*迭代* - 除非你正好有兩個鍵,即分配必然會失敗。 – jonrsharpe

+1

爲什麼不先試着在my_dict.items()中使用'for:object(對象)'來更好地瞭解你正在迭代的內容? – TigerhawkT3

回答

2

它返回項目列表(在python3 dict_items對象),你不能將它們分配給兩個變量。如果你想單獨拿到鑰匙和值,你可以使用dict.keys()dict.values()屬性:

>>> my_dict.items() 
[('bananas', 312), ('oranges', 525), ('peaches', 154), ('strawberries', 267), ('boysenberry', 432), ('apricot', 321), ('plum', 143), ('pears', 217), ('apples', 430), ('blueberry', 179), ('blackberry', 266)] 
>>> 
>>> k, v = my_dict.keys(), my_dict.values() 
>>> 
>>> k 
['bananas', 'oranges', 'peaches', 'strawberries', 'boysenberry', 'apricot', 'plum', 'pears', 'apples', 'blueberry', 'blackberry'] 
>>> 
>>> v 
[312, 525, 154, 267, 432, 321, 143, 217, 430, 179, 266] 
+1

*咳嗽*蟒蛇3 *咳嗽* – jonrsharpe