Home > other >  Stuck after creating the dictionary, any guidance on what to do after?
Stuck after creating the dictionary, any guidance on what to do after?

Time:10-25

This is the question - '''Given a list of strings, create a dictionary, where keys are the strings and the values are the number of times the corresponding string repeats in the list. Do not use any additional libraries.

Example:

>>> problem1(['Hello', 'Hello', 'Friends', 'Friends', 'Friends', 'Home'])
{'Hello': 2, 'Friends': 3, 'Home': 1}

This is my code:

def problem2(mystrings):
    mydct = {}

    for x in mystrings:

        mydct = [mystrings]

    for  in mydct:

        return mydct


print (problem2(['Hello', 'Hello', 'Friends', 'Friends', 'Friends', 'Home']))

I need help on how to make the keys into strings and the values into the number of times the string shows up, I can't figure out how to do it. Any help is appreciated.

CodePudding user response:

You could simply use collections.Counter

>>> l = ['Hello', 'Hello', 'Friends', 'Friends', 'Friends', 'Home']
>>> c = Counter(l)
>>> c
Counter({'Friends': 3, 'Hello': 2, 'Home': 1})
>>> dict(c)
{'Hello': 2, 'Friends': 3, 'Home': 1}

so your function should be like

from collections import Counter

def problem2(mystrings):
    return dict(Counter(mystrings))

if for any reasons, you are not allowed collections.Counter which is part of the Python's standard library, do the following:

def problem2(mystrings):
    counter = {}
    for word in mystrings:
        counter[word] = counter.get(word, 0)   1

    return counter

CodePudding user response:

words = ['Hello', 'Hello', 'Friends', 'Friends', 'Friends', 'Home']
result = {}

for word in words:
    if word not in result:
        result[word] = 1
    else:
        result[word]  = 1
print(result)  # {'Hello': 2, 'Friends': 3, 'Home': 1}

Note that we first want to check whether there's a key already in the dictionary because if we just run result[word] = 1 we'll get a KeyError since there's no key in the dictionary with that name.

  • Related