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

having only 1x value in a list in a dictionary

I want to create a dict with the occurence of the letter from a string as key and the letters which appear that many times as values.

My desired output with an example "occurence" should look like this:

{1: ['o', 'u', 'n'], 3: ['c'], 2: ['r', 'e']}

Right now it looks 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

{1: ['o', 'u', 'n'], 3: ['c', 'c', 'c'], 2: ['r', 'r', 'e', 'e']}

My code right now:

letters = list(text)
new_dict = {}
for elements in list(text):
    if letters.count(elements) not in new_dict:
        new_dict[letters.count(elements)] = [elements]
    else: 
        new_dict[letters.count(elements)].append(elements)
return new_dict

>Solution :

check if the letter is already in the dict and only if not add it:

letters = list(text)  # this line is not needed
new_dict = {}
for elements in list(text):  # `for elements in text:` works just fine
    if letters.count(elements) not in new_dict:  # text.count(...) works just like letters.count(...)
        new_dict[letters.count(elements)] = [elements]
    else:  # can be simpified to `elif elements not in new_dict[...]:`
        if elements not in new_dict[letters.count(elements)]:  # check if the character is already present
            new_dict[letters.count(elements)].append(elements)
return new_dict

btw. you don’t have to convert the string to list to be iterable, support membership testing (a in b) or have a count method.
all of this also works with strings.

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