使用 .get() 方法将列表的元素添加到字典中

Adding elements of a list into a dictionary using .get() method

我有一个元素列表 [1, 2, 5, 2, 3, 7, 5, 8]。我想把它放入字典中,这样它就会变成 "key : how many times it appears in the list",所以字典看起来像这样:

{"1:1", "2:2", "5:2", "3:1", "7:1", "8:1"}

该解决方案应该适用于任何列表。

我对列表进行了迭代,但在将元素添加到字典中时收到错误消息。

given = (1, 2, 5, 2, 3, 7, 5, 8)
midwayDict = dict()
for element in given:
    midwayDict = midwayDict.get(element, 0)
print(midwayDict)

它给我的只是" AttributeError: 'int' object has no attribute 'get' "。 我使用的方法有问题吗?或者我应该使用不同的方式?

我刚才看到有人在用这个,但我找不到具体的操作方法。

您的代码中的错误是

given = (1, 2, 5, 2, 3, 7, 5, 8)
midwayDict = dict()
for element in given:
    midwayDict = midwayDict.get(element, 0)  # <- you are assigning 0 to dict so in next iteration you are accessing .get method on integer so its saying there is no get method on int object
print(midwayDict)

应该是

given = (1, 2, 5, 2, 3, 7, 5, 8)
midwayDict = dict()
for element in given:
    _ = midwayDict.setdefault(element, 0)
    midwayDict[element] += 1
print(midwayDict)

更好的是

from collections import Counter
given = (1, 2, 5, 2, 3, 7, 5, 8)
print(Counter(given))

您的代码中只有一个错误。

given = (1, 2, 5, 2, 3, 7, 5, 8)
midwayDict = dict()
for element in set(given):
    midwayDict[element] = midwayDict.get(element, 0)+1 # edited
print(midwayDict)

更好的方法是使用字典理解。

given = (1, 2, 5, 2, 3, 7, 5, 8)

d = {a:given.count(a) for a in set(given)}
print(d)