benthediver99
benthediver99

Reputation: 27

Trying to create a dictionary from a list of numbers, but list index is out of range

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):

function below creates a dictionary from num_list

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

Answers (3)

felipe
felipe

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

lenik
lenik

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

asafpr
asafpr

Reputation: 357

  1. This is an inefficient implementation, it's O(n^2), you can solve it in O(n)
  2. You didn't initialize num_dict, you can use defaultdict:

    num_dict = defaultdict(list)

  3. num_list[i] will not be in num_dict.values() because the values() are lists and num_list[i] is an integer (you assume)

  4. 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

Related Questions