Reputation: 27
I'm trying to make a function that creates a dictionary with number of occurrences being the keys and each key having a list of numbers that occurred that many times as values
The part where it messes up is at the line:
if num_list[i] not in num_dic.values():
or also messes up at:
if num_list.index(i) == num_list.index(j):
def createDic(num_list):
num_dic = {}
num_occurs = 0
for i in num_list:
if num_list[i] not in num_dic.values():
for j in num_list:
if num_list.index(i) == num_list.index(j):
num_occurs += 1
num_dic[num_occurs].append(num_list[i])
num_occurs = 0
return num_dic
Upvotes: 0
Views: 59
Reputation: 8025
data = ["a", "b", "b", "c", "c", "c", "d", "d", "d"]
info = {}
for i in data:
count = data.count(i)
if count not in info:
info[count] = [i]
elif i not in info[count]:
info[count].extend(i)
print(info)
Outputs:
{1: ['a'], 2: ['b'], 3: ['c', 'd']}
A better solution, but uses an import:
from collections import Counter
data = ["a", "b", "b", "c", "c", "c", "d", "d", "d"]
info = {}
for o, c in Counter(data).items():
info[c] = [o] if c not in info else info[c] + [o]
print(info)
Outputs:
{1: ['a'], 2: ['b'], 3: ['c', 'd']}
Upvotes: 1
Reputation: 23536
You should do this differently, first count the occurences, then convert that to the dict:
>>> a = [1,1,2,3,4,4,4]
>>> from collections import Counter, defaultdict
>>> c = Counter(a)
>>> c
Counter({4: 3, 1: 2, 2: 1, 3: 1})
>>> occurences = defaultdict(list)
>>> for a,b in c.items() :
... occurences[b].append(a)
...
>>> occurences
defaultdict(<type 'list'>, {1: [2, 3], 2: [1], 3: [4]})
>>> dict(occurences)
{1: [2, 3], 2: [1], 3: [4]}
Upvotes: 1
Reputation: 357
You didn't initialize num_dict
, you can use defaultdict:
num_dict = defaultdict(list)
num_list[i]
will not be in num_dict.values()
because the values()
are lists and num_list[i]
is an integer (you assume)
You iterate over the list with i
but then think it's the index rather than the values in the list, you should replace it with for i in range(len(num_list))
(same for j)
Upvotes: 0