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

Time:05-03

I have a list of elements (1, 2, 5, 2, 3, 7, 5, 8). I want to put it into a dictionary so it would go "key : how many times it appears in the list", so the dictionary looks something like as follows: {"1:1", "2:2", "5:2", "3:1", "7:1", "8:1"}. The solution should be applicable to any list.

I did the iteration of the list, but am receiving an error when it comes to adding the elements into the dictionary.

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

All it gives me is " AttributeError: 'int' object has no attribute 'get' ". Is something wrong with the method I'm using? or should I use a different way?

I saw this being used somewhere a while ago, but I am not being able to find where of how exactly to do this. Thank you for your help in advance

CodePudding user response:

The error in your code is

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)

Should be

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

Better is

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

CodePudding user response:

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

The better way to do this is using dictionary comprehension.

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

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

  • Related