Additionally, if the original dictionary has only one value, it gets a score of 1. For example, a dict that looks like this:
{
'q1': ['d184', 'd29', 'd879', 'd880'],
'q2': ['d12', 'd15', 'd658'],
'q3': ['d10']
}
Would become the following:
{
'q1': [5, 4, 3, 2],
'q2': [4, 3, 2],
'q3': [1]
}
This is a start for a dictionary with 2 keys, not including the 1-value situation:
dct = {
'q1': ['d184', 'd29', 'd879', 'd880'],
'q2': ['d12', 'd15', 'd658']
}
new_dict = {}
new_values = []
for key in dct.keys():
length = len(dct[key])
values = []
for num in range(length 2):
values.append(num)
sort_ed = sorted(values, key=int, reverse=True)[:-2]
new_values.append(sort_ed)
print(new_values)
[[5, 4, 3, 2], [4, 3, 2]]
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
.
CodePudding user response:
Here is a solution, using range
to rank the elements
from collections import defaultdict
d = {
'q1': ['d184', 'd29', 'd879', 'd880'],
'q2': ['d12', 'd15', 'd658'],
'q3': ['d10']
}
ranks_ = defaultdict(list)
for k, v in d.items():
rank_inc = bool(len(v) > 1) # If length of list is > 1 decrement by 1
for i in range(len(v), 0, -1):
ranks_[k].append(i rank_inc)
print(ranks_)
defaultdict(<class 'list'>, {'q1': [5, 4, 3, 2], 'q2': [4, 3, 2], 'q3': [1]})