Python: Dictionary to Spare Vector

Question:

I am new to Python and programming in general. I was working on Pyschool exercises Topic 8, Q 11 on converting Dictionary to Spare Vectore.

I was asked to Write a function that converts a dictionary back to its sparese vector representation.

Examples

>>> convertDictionary({0: 1, 3: 2, 7: 3, 12: 4})
[1, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 4]
>>> convertDictionary({0: 1, 2: 1, 4: 2, 6: 1, 9: 1})
[1, 0, 1, 0, 2, 0, 1, 0, 0, 1]
>>> convertDictionary({})
[]

I have attempted many times. Below is the latest code I have:

def convertDictionary(dictionary):
    k=dictionary.keys()
    v=dictionary.values()
    result=[]
    for i in range(0,max(k)):
        result.append(0)
        for j in k:
            result[j]=v[k.index(j)]
    return result

The returned error is:

Traceback (most recent call last):
File "Code", line 8, in convertDictionary
IndexError: list assignment index out of range

Could anyone help me? Thank you so much!

Asked By: GSu

||

Answers:

Something like this should suffice:

M = max(dictionary, default=0)
vector = [dictionary.get(i, 0) for i in range(M)]

Translated into a plain old for-loop

M = max(dictionary, default=0)
vector = []
for i in range(M):
    vector.append(dictionary.get(i, 0))

The get method lets you provide a default as a second argument in case the key is missing. Once you get more advance you could use a defaultdict

Edit: the default parameter for max requires Python >3.4 . You can either use exception handling (generally prefered) or explicit checks for empty dictionary to deal with that case if you have earlier versions.

Answered By: juanpa.arrivillaga

Your code works logically fine, but you have a problem of indentation. Your function should be:

def convertDictionary(dictionary):
    k=dictionary.keys()
    v=dictionary.values()
    result=[]
    for i in range(0,max(k)):
        result.append(0)
    for j in k:
        result[j]=v[k.index(j)]
    return result

The problem is that your second for was inside of the first. What you want is to build a list with max(k) elements and then put the right values into it. Then, the two for loops should be one after the other, rather than one inside of the other.

Answered By: Right leg

M = max(dictionary, default=0)

vector = [dictionary.get(i, 0) for i in range(M+1)]

Should always add 1 to range as final value is not inclusive so if range is 12 then only 11 iterations

Answered By: Nithin koilpillai
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.