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

Creating a dictionary in python by condition

I want to get a dictionary from an available numeric list, divided by digits and their number in a string.

My inputs:

num_list = list('181986336314')

I need to get a dictionary like this:

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

mydict = {1: 111, 2: None, 3: 333, 4: 4, 5: None, 6: 66, 7: None, 8: 88, 9: 9}

>Solution :

One way to do it is to post engineer your counter result

counter = Counter(num_list)
my_dict = {}
for i in range(1, 10):
    if (str(i) in counter.keys()):
        my_dict[i] = int(str(i) * counter[str(i)])
    else:
        my_dict[i] = None
    
print(my_dict)
> {1: 111, 2: None, 3: 333, 4: 4, 5: None, 6: 66, 7: None, 8: 88, 9: 9}
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