user1485195
user1485195

Reputation: 19

Dictionary to Sparse Vector Python

please help me on this homework:

makeA({0: 1, 2: 1, 4: 2, 6: 1, 9: 1})

the output should be like this:

[1, 0, 1, 0, 2, 0, 1, 0, 0, 1]

Upvotes: 0

Views: 2904

Answers (2)

Maria Zverina
Maria Zverina

Reputation: 11163

Yes, you could do the default value in list comprehension. But I think it's nicer style to let the defaultdict class do it for you. And you get more readable code to boot!! :-)

from collections import defaultdict

def makeA(d):
    dd = defaultdict(int, d)
    return [dd[n] for n in range(10)]


print makeA({0: 1, 2: 1, 4: 2, 6: 1, 9: 1})

Upvotes: 1

Kos
Kos

Reputation: 72231

Try a list comprehension:

def makeA(d, default=0):
    """Converts a dictionary to a list. Pads with a default element

    Examples:

    >>> makeA({0: 1, 2: 1, 4: 2, 6: 1, 9: 1})
    [1, 0, 1, 0, 2, 0, 1, 0, 0, 1]

    >>> makeA({3: 'kos'},'')
    ['', '', '', 'kos']

    """
    maxElem = max(d)
    return [d.get(x, default) for x in range(maxElem+1)]

The first line of the function body finds the maximum key in the dict (because dict objects yield their keys when iterated over). If the maximum key is 5, you'd need an array of 6 elements [0..6].

The last line uses a list comprehension over a sequence 0 .. maxElem, and for each value of this sequence, assigns either d's value for this key or 0 if not present.

Upvotes: 5

Related Questions