2015-11-02 82 views
0

我有一個與字典的鍵值相同的列表。我想編寫一個代碼,它可以根據字典的值對列表中的值進行多少次操作(例如,將它們加1)。通過字典對列表進行迭代

因此,例如,

listy=['dgdg','thth','zuh','zuh','thth','dgdg'] 
dicty = {'dgdg':1, 'thth':2, 'zuh':5} 

我試過這段代碼:

def functy (listx,dictx): 
    for i in range (0, len(listx)): 
     for k,v in dictx: 
      if listx[i]==k: 
       v=v+1 
      else: 
       pass 
functy(listy, dicty) 

但它提出了這樣的錯誤:

Traceback (most recent call last): 
    File "C:\Python34\8.py", line 12, in <module> 
    functy(listy, dicty) 
    File "C:\Python34\8.py", line 6, in functy 
    for k,v in dictx: 
ValueError: too many values to unpack (expected 2) 

你能告訴我,爲什麼它不工作,我怎麼能做到嗎?

回答

5

dict.__iter__將默認參考dict.keys()

因爲你想同時得到key,其價值應該是

for k,v in dictx.items(): 

這將產生一個元組列表:

>>> a={1:2,2:3,3:4} 
>>> a.items() 
[(1, 2), (2, 3), (3, 4)] 

iteritems也可以,但是從發電,而不是收益率一個列表:

>>> a.iteritems() 
<dictionary-itemiterator object at 0x00000000030115E8> 

但是,你應該採取考慮到通過鍵直接索引,否則你的任務v=v+1不會被持久化到字典:

def functy (listx,dictx): 
    for item in listx: 
     if item in dictx: 
      dictx[item]+=1 

>>> listy=['dgdg','thth','zuh','zuh','thth','dgdg'] 
>>> dicty = {'dgdg':1, 'thth':2, 'zuh':5}    
>>> print dicty 
{'thth': 2, 'zuh': 5, 'dgdg': 1} 
>>> functy(listy, dicty) 
>>> print dicty 
{'thth': 4, 'zuh': 7, 'dgdg': 3} 
0

dictx.items()而不是dictx。當試圖迭代dictx時,您只收到密鑰。

+0

可以在錯誤代碼OP看到使用[Python的3.4](https://docs.python.org/3/whatsnew/3.0.html#views-and-iterators-instead-列表) –

+0

啊,的確如此。感謝那。 – mic4ael

0

您可以重複這樣的詞典:

for k in dictx: 
    v = dictx[k] 
4

你缺少具有點字典,這是你可以直接用鍵索引它而不是迭代它:

def functy(listx, dictx): 
    for item in listx: 
     if item in dictx: 
      dictx[item] += 1 
4

它看起來像你試圖使用字典作爲計數器。如果是這樣的話,爲什麼不使用內置的Python Counter

from collections import Counter 
dicty = Counter({'dgdg':1, 'thth':2, 'zuh':5}) 
dicty += Counter(['dgdg','thth','zuh','zuh','thth','dgdg']) 

# dicty is now Counter({'zuh': 7, 'thth': 4, 'dgdg': 3}) 
+0

'some_count + = Counter(some_iterable)'與'some_count.update(some_iterable)'具有相同的效果。 –

2

我建議你使用collections.Counter,這是一個dict子類計算哈希的對象。

>>> import collections 
>>> count_y = collections.Counter(dicty) # convert dicty into a Counter 
>>> count_y.update(item for item in listy if item in count_y) 
>>> count_y 
Counter({'zuh': 7, 'thth': 4, 'dgdg': 3}) 
-1
listy=['dgdg','thth','zuh','zuh','thth','dgdg'] 
dicty = {'dgdg':1, 'thth':2, 'zuh':5} 

# items() missed and also dicty not updated in the original script 
def functy (listx,dictx): 
    for i in range (0, len(listx)): 
     for k,v in dictx.items(): 
      if listx[i]==k: 
       dictx[k] += 1 
      else: 
       pass 
functy(listy, dicty) 

print(dicty) 

{'dgdg': 3, 'thth': 4, 'zuh': 7}