Insert a list of numbers into a dictionary

Following on from my previous question: here
I Asked how to check if current element it’s smaller than the next elements and count them.

Now, I want to do something else, I want to create a dictionary that stores the values in the following way:

input:

 A = [5, 4, 3, 2]

output:

{'key_5': [4,3,2], 'key_4': [3,2], 'key_3': [1], 'key_2': [0]}

Explanation:

  • 4,3,2 is less than 5
  • 3,2 is less than 4
  • 2 is less than 3
  • and 2 is the last element and nothing is less than it.
A = [5, 4, 3, 2]
res = {}
dp = [0]*len(A)
for i in range(len(A)):
    for j in range(i, len(A)):
        if A[i] > A[j]:
            dp[i] += 1 #Counts how many times each element appears in the list.
            res[f'key_{A[i]}'] = A[j] #Trying to add elements to dictionary.

print(res)

And my output is:

{'key_5': 2, 'key_4': 2, 'key_3': 2}

>Solution :

Using dict/list comprehensions:

>>> A = [5, 4, 3, 2]
>>> {f"key_{n}": [i for i in A if i < n] or [0] for n in A}
{'key_5': [4, 3, 2], 'key_4': [3, 2], 'key_3': [2], 'key_2': [0]}

Leave a Reply