# Creating histogram from list

74
July 21, 2021, at 09:20 AM

This question was a part of the the interview process and I couldn't figure it out. Given a list of integers, create a histogram where the output is a dictionary. The key are the elements in the list and the values are the count of elements in the list. For example : inputlist:[2,3,4,2,5,7,3,2,4] and expected output = {2:3,3:2,4:2..} I know there has to be a loop iterating over the list and then inserting those values in the dictionary. But I messed up on the syntax bad. Would appreciate if somebody could guide me with syntax or pseudocode. HELP!

Answer 1

For future reference you can't just provide the question, you need to provide a minimum reproducible example.

Here's the answer anyways:

``````output = {}
inputlist = [2,3,4,2,5,7,3,2,4]
for num in inputlist:
if num in output:
output[num] += 1
else:
output[num] = 1
print(output)
``````
Answer 2

Try this:

``````from collections import Counter
inputlist = [2,3,4,2,5,7,3,2,4]
freq_counter = Counter(inputlist)
print(freq_counter)
``````
Answer 3

This would be my solution using dictionary comprehension:

``````inputlist = [2,3,4,2,5,7,3,2,4]
result = {k:inputlist.count(k) for k in set(inputlist)}
``````

However I agree that `Counter` from `collections` would probably perform better as the `inputlist` would get bigger (see list.count() vs Counter() performance)

POPULAR ONLINE

READ ALSO

### I keep getting Error: ER_EMPTY_QUERY: QUERY was empty

I'm trying to make a register pageWhen I enter the data that needs to be registered, it shows up on the console followed by Error: ER_EMPTY_QUERY

50

### Javascript Operators - Combining Nullish Coalescing with Ternary

So I have some code where I'm essentially trying to do an if, else if, else statement in one line, but based on nullishness instead of truthiness

58

### Django - JQuery autocomplete custom select from multiple fields

I have a user search that autocompletes by both ticker and nameThe search results come back as "{{ticker}} - {{name}}"

81

### Jython importing a module by changing sys.path in a PyInterpreter and PySystemState still raises an import error

Here's a very simple elaboration of said problem

83