通过字典迭代列表

时间:2015-11-02 19:10:43

标签: python dictionary

我有一个列表,其值与字典的键相同。我想写一个代码,它对字典的值做了一些事情(例如将它们增加一个),就像它们的密钥出现在列表中一样多次。

所以,例如

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)

你能告诉我它为什么不起作用以及如何制作它?

7 个答案:

答案 0 :(得分:5)

默认情况下,

init2会引用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

答案 1 :(得分:4)

你错过了拥有字典的重点,你可以直接用密钥对其进行索引,而不是迭代它:

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

答案 2 :(得分: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})

答案 3 :(得分: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})

答案 4 :(得分:0)

dictx.items()代替dictx。尝试迭代dictx时,您只收到密钥。

答案 5 :(得分:0)

您可以像这样迭代字典:

let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/d8bb95982be8a11a2308e779bb9a9707ebe42ede/sample_json"
Alamofire.request(.GET, URL).responseObject("data") { (response: 
Response<WeatherResponse, NSError>) in

let weatherResponse = response.result.value

print(weatherResponse?.location)
if let threeDayForecast = weatherResponse?.threeDayForecast {
    for forecast in threeDayForecast {
        print(forecast.day)
        print(forecast.temperature)           
     }
  }
}

答案 6 :(得分:-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}