Insert a list of numbers into a dictionary

Question:

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}
Asked By: Amit Ben-David

||

Answers:

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]}
Answered By: Samwise
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.