Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to manipulate same dictionary

Tags:

python

A very naive question.. I have the following function:

def vectorize(pos, neg):
    vec = {item_id:1 for item_id in pos}
    for item_id in neg:
        vec[item_id] = 0
    return vec

Example:

>>> print vectorize([1, 2] [3, 200, 201, 202])
{1: 1, 2: 1, 3: 0, 200: 0, 201: 0, 202: 0}

I feel, this is too verbose in python.. Is there a more pythonic way to do this... Basically, I am returning a dictionary whose values are 1 if its in pos (list) and 0 otherwise?

like image 952
frazman Avatar asked Dec 06 '25 17:12

frazman


2 Answers

I'm not particularly sure if this is more pythonic... Maybe a little bit more efficient? Dunno, really

pos = [1, 2, 3, 4]
neg = [5, 6, 7, 8]

def vectorize(pos, neg):
    vec = dict.fromkeys(pos, 1)
    vec.update(dict.fromkeys(neg, 0))
    return vec

print vectorize(pos, neg)

Outputs:

{1: 1, 2: 1, 3: 1, 4: 1, 5: 0, 6: 0, 7: 0, 8: 0}

But I like your way too... Just giving an idea here.

like image 176
BorrajaX Avatar answered Dec 08 '25 09:12

BorrajaX


I'd probably just do:

def vectorize(pos, neg):
    vec = {}
    vec.update((item, 1) for item in pos)
    vec.update((item, 0) for item in neg)
    return vec

But your code is fine as well.

like image 35
Bill Lynch Avatar answered Dec 08 '25 07:12

Bill Lynch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!