0

For example, I have a list that has copies of certain items:

list = [item1,item2,item2,item3,item4,item4]

And I want to iterate over list and put each item in an empty dictionary dict = {}

for item in list: # if the item isn't in the dict, add it and set value to 1 # if item is already in dict, increment value by one

What is the best way to manipulate the dictionary and using the for loop variable item?

1 Answers1

0

You can use defaultdict

from collections import defaultdict
diction = defaultdict(lambda:0, {})
for item in your_list:
    diction[item] += 1

All your keys will be initialized to 1 if they are not in the dict already or incremented otherwise.

user2969402
  • 1,221
  • 3
  • 16
  • 26