简体   繁体   中英

list comprehension for dictionary values, assigning 0 or 1 based on value

I want to use a list comprehension to create a vector of 0s and 1s based on values in a dictionary.

In this example, I want every positive number to be returned as 1 and every 0 number to remain 0. However, I need the solution changeable such that if I wanted to set the threshold to 0.25 (instead of 0) I could easily make that change.

test_dict = {'a':0.6, 'b':0, 'c':1, 'd':0.5}
skill_vector = [1 for skill.values() in test_dict if skill.values > 0 else 0]

Desired output: [1,0,1,1]

Edit: As wiser minds have pointed out, dictionary are not ordered so the output would not be of use. In light of this, I intend to make use of the OrderedDict subclass.

You could cast the boolean from your test to an int rather than using the if/else pattern:

test_dict = {'a':0.6, 'b':0, 'c':1, 'd':0.5}

threshold = 0
[int(v > threshold) for v in test_dict.values()]
# [1, 0, 1, 1]

This assumes you're using a version of python that keeps the keys in insert order.

You can use the ternary operator:

Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> test_dict = {'a':0.6, 'b':0, 'c':1, 'd':0.5}
>>> [1 if x > 0 else 0 for x in test_dict.values()]
[1, 0, 1, 1]

You can also use a dictionary comprehension to ensure the result is mapped to the correct key:

>>> {k:1 if v > 0 else 0 for k,v in test_dict.items()}
{'a': 1, 'b': 0, 'c': 1, 'd': 1}

If you want to use the skill_values function:

def skill_values(x):
     return skill_values >= .25

skill_vector = [1 if skill_values(x) else 0 for x in test_dict.values()]

or incorporating the mapping to int from another answer

skill_vector = [int(skill_values(x)) for x in test_dict.values()]

Code:

test_dict = {'a':0.6, 'b':0, 'c':1, 'd':0.5}
skill_vector = list(map(int, map(bool, test_dict.values())))

Output:

[1, 0, 1, 1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM