Additionally, if the original dictionary has only one value, it gets a score of 1. For example, a dict that looks like this:
JavaScript
x
6
1
{
2
'q1': ['d184', 'd29', 'd879', 'd880'],
3
'q2': ['d12', 'd15', 'd658'],
4
'q3': ['d10']
5
}
6
Would become the following:
JavaScript
1
6
1
{
2
'q1': [5, 4, 3, 2],
3
'q2': [4, 3, 2],
4
'q3': [1]
5
}
6
This is a start for a dictionary with 2 keys, not including the 1-value situation:
JavaScript
1
17
17
1
dct = {
2
'q1': ['d184', 'd29', 'd879', 'd880'],
3
'q2': ['d12', 'd15', 'd658']
4
}
5
new_dict = {}
6
new_values = []
7
for key in dct.keys():
8
length = len(dct[key])
9
values = []
10
for num in range(length+2):
11
values.append(num)
12
sort_ed = sorted(values, key=int, reverse=True)[:-2]
13
new_values.append(sort_ed)
14
print(new_values)
15
16
[[5, 4, 3, 2], [4, 3, 2]]
17
That’s what I want for the values, now I just need to set the keys of a new dictionary to the keys of the original one, and assign the values from new_values
.
Advertisement
Answer
Here is a solution, using range
to rank the elements
JavaScript
1
18
18
1
from collections import defaultdict
2
3
d = {
4
'q1': ['d184', 'd29', 'd879', 'd880'],
5
'q2': ['d12', 'd15', 'd658'],
6
'q3': ['d10']
7
}
8
9
ranks_ = defaultdict(list)
10
11
for k, v in d.items():
12
rank_inc = bool(len(v) > 1) # If length of list is > 1 decrement by 1
13
14
for i in range(len(v), 0, -1):
15
ranks_[k].append(i + rank_inc)
16
17
print(ranks_)
18
JavaScript
1
2
1
defaultdict(<class 'list'>, {'q1': [5, 4, 3, 2], 'q2': [4, 3, 2], 'q3': [1]})
2