Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading