This is a test version of Biostars. For the public version, visit https://www.biostars.org.
how to score the values in a dictionary in python

I have a dictionary like this small example:

raw = {'id1': ['KKKKKK', 'MMMMMMMMMMMMMMM'], 'id2': ['KKKKKM', 'KKKKKK']}

as you see the values are are list. I would like to replace the list with a number which is score. I score each character in the list based on their length. if the length is 6 to 11 they would get 1, from 12 to 17 would be 2 and 18 and longer would get 3. then I add up all scores per id and would have one score per id. here is small example:

score = {'id1': 3, 'id2': 2}

I wrote the following code but did not give what I want:

score = {}
for val in raw.values():
    for i in val:
        if len(i) >=6<12:
            sc = 1
        elif len(i) >=12<18:
            sc = 2
        else:
            sc = 3
        score[raw.keys()] = sc
sequence

2 answers

Or even simpler and faster (only 1 if statement, instead of 3):

raw = {'id1': ['KKKKKK', 'MMMMMMMMMMMMMMM'], 'id2': ['KKKKKM', 'KKKKKK']}

score = {}
for k, v in raw.items():
    score[k] = sum([int((len(s)/6.0)) if len(s)<18 else 3 for s in v])
print(score)

Output:

{'id2': 2, 'id1': 3}

Sorry my python is a bit rusty at the moment, but this works for me.

raw = {'id1': ['KKKKKK', 'MMMMMMMMMMMMMMM'], 'id2': ['KKKKKM', 'KKKKKK']}

    for k, v in raw.iteritems():

        print k

        score = 0

        for val in v:

            if len(val) >= 6 | len(val) <= 11:

                score = score + 1

            if len(val) >= 12 | len(val) <= 17:

                score = score + 2

            if len(val) >= 18:

                score = score + 3

        raw[k] = score


 print raw

Log in to answer this question.