This question is about nested dictionary comprehension and I have referred the link1 and link2 before asking this.
I have a list whose first element is None and the remaining of it is a list of sorted positive numbers.
sorted_ar = [None, 10, 10, 12, 12, 12, 15, 25]
My requirement is to build a dictionary as:
key_dict = {10: [3, 2], 12: [12, 3], 15: [6, 1], 25: [7, 1]}
The values of the dictionary are a two element list, first element is the sum of indexes of the occurrences of key, second is the number of occurrences.
For example for element 12,
sum of indexes = 3+4+5 = 12 and number of occurrences is 3.
The following code does it.
key_dict = {k:[0,0] for k in sorted_ar if k!=None}
for i in range(len(sorted_ar)):
if sorted_ar[i]:
key_dict[sorted_ar[i]][0] += i
key_dict[sorted_ar[i]][1] += 1
My requirement is to prepare the key_dict dictionary using dictionary comprehension.
My attempt:
key_dict = {
sorted_ar[i]:[ key_dict[sorted_ar[i]][0] + i,key_dict[sorted_ar[i]][0] + 1]
for i in range(1,len(sorted_ar)) if sorted_ar[i]!=None
}
But this is giving some erroneous result as
key_dict = {10: [2, 1], 12: [5, 1], 15: [6, 1], 25: [7, 1]}
How should I write the dictionary comprehension in this case?