I'm new to Python coming from a JavaScript background. I'm trying to find a solution for the following. I want to build a dictionary from list data on the fly. I only want to add the list entries that are unique, with a count of 1. Any repeats thereafter I want to keep a count of. Hence from a list containing ["one", "two", "three", "one"]
I want to build a dictionary containing {'one': 2, 'two': 1, 'three': 1}
I mean to use the list entries as keys and use the dict values for the respective counts. I can't seem to get Python to do it. My code follows. It's currently adding unpredictably to the dictionary totals. I only seem to be able to add the unique entries in the list this way. No luck with any totals. I wanted to ask if I'm on the wrong track or if I'm missing something with this approach. Can someone please help?
import copy
data = ["one", "two", "three", "one"]
new_dict = {}
# build dictionary from list data and only count (not add) any redundant entries
for x in data:
dict_copy = copy.deepcopy(new_dict) # loop through a copy (safety)
for y in dict_copy:
if x in new_dict: # check if an entry exists?
new_dict[y] += 1 # this count gives unpredictable results !!
else:
new_dict[x] = 1 # new entry
else:
new_dict[x] = 1 # first entry
print(new_dict)