Home > Mobile >  having only 1x value in a list in a dictionary
having only 1x value in a list in a dictionary

Time:11-07

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:

{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

CodePudding user response:

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.

CodePudding user response:

You can do it fairly succinctly using a Collections.Counter class to count the occurrences of each letter:

from collections import Counter

text = 'ouncccrree'
counter = Counter(text)
new_dict = {}
for k, v in counter.items():
    new_dict[v] = new_dict.get(v, [])   [k]
print(new_dict)  # -> {1: ['o', 'u', 'n'], 3: ['c'], 2: ['r', 'e']}
  • Related