How can I make a function with a dictionary of occurrences from list I set later?
Question:
I have a set of functions that are meant to set a dictionary with the key being the character that occurs in the lists and the items being the number of occurrences but when I run the code the dictionary is empty.
This is my actual code
def uniqueOccurrence(item1, item2, item3):
d = {}
for i in d:
if i in d:
d[i] = d[i] + 1
else:
d[i] = 1
return d
def main():
list1 = [1]
list2 = [1,2]
list3 = [1,2,3]
print(uniqueOccurrence(list1, list2, list3))
if __name__ == "__main__":
main()
It is supposed to return something like this
{1: 3, 2: 2, 3: 1}
but is returning an empty dictionary
{}
Answers:
You do not use your input parameters in the function, you can do it like this:
def count_elements(*lists):
element_count = {}
for lst in lists:
for element in lst:
if element in element_count:
element_count[element] += 1
else:
element_count[element] = 1
return element_count
count_elements(list1, list2, list3)
Or use a Counter:
from collections import Counter
def count_elements(*lists):
element_count = Counter()
for lst in lists:
element_count.update(lst)
return element_count
count_elements(list1, list2, list3)
I have a set of functions that are meant to set a dictionary with the key being the character that occurs in the lists and the items being the number of occurrences but when I run the code the dictionary is empty.
This is my actual code
def uniqueOccurrence(item1, item2, item3):
d = {}
for i in d:
if i in d:
d[i] = d[i] + 1
else:
d[i] = 1
return d
def main():
list1 = [1]
list2 = [1,2]
list3 = [1,2,3]
print(uniqueOccurrence(list1, list2, list3))
if __name__ == "__main__":
main()
It is supposed to return something like this
{1: 3, 2: 2, 3: 1}
but is returning an empty dictionary
{}
You do not use your input parameters in the function, you can do it like this:
def count_elements(*lists):
element_count = {}
for lst in lists:
for element in lst:
if element in element_count:
element_count[element] += 1
else:
element_count[element] = 1
return element_count
count_elements(list1, list2, list3)
Or use a Counter:
from collections import Counter
def count_elements(*lists):
element_count = Counter()
for lst in lists:
element_count.update(lst)
return element_count
count_elements(list1, list2, list3)