how to score the values in a dictionary in python
2
3
Entering edit mode
8.0 years ago
ashkan ▴ 160

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 • 4.1k views
ADD COMMENT
0
Entering edit mode
for k, v in raw.iteritems():
     sc = 0
     for i in v:
        if 6 <=  i < 12:
           sc += 1
        elif 12 <=  i < 18:
           sc += 2
        else :
           sc += 3
    score[k] = sc

bonus interval comparison or chained comparison operators

Good luck :)

ADD REPLY
3
Entering edit mode
8.0 years ago

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}
ADD COMMENT
0
Entering edit mode
8.0 years ago
chris86 ▴ 400

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
ADD COMMENT

Login before adding your answer.

Traffic: 2207 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6