[英]Iterate a list through a dictionary
I have a list with the same values as the keys of a dictionary. 我有一个列表,其值与字典的键相同。 I want to write a code that does something to the values of the dictionary (eg increases them by one) as many times as their key appears in the list. 我想编写一个对字典的值执行某种操作的代码(例如,将其值增加一),使其次数出现在列表中。
So eg 所以例如
listy=['dgdg','thth','zuh','zuh','thth','dgdg']
dicty = {'dgdg':1, 'thth':2, 'zuh':5}
I tried this code: 我尝试了这段代码:
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)
But it raises this error: 但这会引发此错误:
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)
Could you tell me why it doesn't work and how I can make it? 你能告诉我为什么它不起作用以及我怎么做吗?
dict.__iter__
will by default refer to dict.keys()
. dict.__iter__
默认情况下将引用dict.keys()
。
Because you want both the key
and its value it should be 因为您既需要key
又需要它的值,所以应该
for k,v in dictx.items():
which will yield a list of tuples: 这将产生一个元组列表:
>>> a={1:2,2:3,3:4}
>>> a.items()
[(1, 2), (2, 3), (3, 4)]
iteritems
is also available, but yields from a generator instead of a list: 也可以使用iteritems
,但它来自生成器而不是列表:
>>> a.iteritems()
<dictionary-itemiterator object at 0x00000000030115E8>
However, you should take into consideration directly indexing by key, otherwise your assignment v=v+1
will not be persisted to the dict: 但是,您应该考虑直接通过键索引,否则您的赋值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}
You're missing the point of having a dictionary, which is that you can index it directly by key instead of iterating over it: 您错过了拥有字典的意义,因为您可以直接通过键为它建立索引,而不必遍历它:
def functy(listx, dictx):
for item in listx:
if item in dictx:
dictx[item] += 1
It looks like you're trying to use a dictionary as a counter. 您似乎正在尝试使用字典作为计数器。 If that's the case, why not use the built-in Python Counter
? 如果是这样,为什么不使用内置的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})
I suggest you use collections.Counter
, which is a dict
subclass for counting hashable objects. 我建议您使用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})
dictx.items()
instead of dictx
. dictx.items()
而不是dictx
。 When trying to iterate over dictx
you are receiving only keys. 尝试迭代dictx
您仅收到密钥。
You can iterate a dictionary like this: 您可以像这样迭代字典:
for k in dictx:
v = dictx[k]
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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.