How to add a new key to a dictionary?

Asked

Viewed 472 times

1

I have the following challenge:

input : "conaz test"

output: {'a': 1, ' ': 1, 'c': 1, 'e': 2, 'o': 1, 'n': 1, ’s': 1, ’t': 2, 'z': 1}

And implemented the following code:

    def contabiliza_letras(string):
        dict = {'a':0,'b':0,'c':0,'d':0,'e':0,'f':0,'g':0,'h':0,'i':0,'j':0,'k':0,'l':0,'m':0,'n':0,'o':0,'p':0,'q':0,'r':0,'s':0,'t':0,'u':0,'v':0,'w':0,'x':0,'y':0,'z':0}
        for letra in string:
            if letra == ' ':
                pass
            else:
                 dict[letra] += 1
       return dict

print(contabiliza_letras("teste conaz"))

And it’s working, but I wanted that, as I was given the letters of the string, I would add the key in the dictionary, so that the answer would be a dictionary containing only the letters that are in the string.

3 answers

4

You can leave the dictionary empty and keep adding the keys as needed, something like this:

def contabiliza_letras(string):
    dict = {}
    for letra in string:
        if not letra == " ":
            dict[letra] = dict.get(letra, 0) + 1
    return dict

And use the method .get() to take the current value of an existing letter, or zero if it does not exist and add it with 1. And in case the key does not exist it will be automatically created in the process.

The result would be like this, but {'t': 2, 'e': 2, 's': 1, 'c': 1, 'o': 1, 'n': 1, 'a': 1, 'z': 1} in your example space is being considered, hence just remove the condition of the if.

2


Instead of creating the dictionary with all letters 0, start it empty: dict={}

When it’s done dict[chaveNova]=NovoValor, it already includes in the dictionary if that key does not exist. Also, as you want to increment the key, you can check if it already exists and otherwise set as initial value "1":

def contabiliza_letras(string):
    dict = {}
    for letra in string:
        if letra == ' ':
            pass
        else:
             if (letra not in dict):
                 dict[letra]=1
             else:
                 dict[letra] += 1
    return dict

print(contabiliza_letras("teste conaz"))
  • Thanks! Thinking a little more implemented a very similar code. Solved the problem! :)

1

If in this challenge you can use Python’s own resources to work with Collections, there is the Counter which serves precisely this purpose:

from collections import Counter

sentence = 'teste conaz'
counter = Counter()

for word in sentence:
    counter.update(word)

# [('t', 2), ('e', 2), ('s', 1), (' ', 1), ('c', 1), ('o', 1), ('n', 1), ('a', 1), ('z', 1)] 
print(counter.most_common())
# {'t': 2, 'e': 2, 's': 1, ' ': 1, 'c': 1, 'o': 1, 'n': 1, 'a': 1, 'z': 1}
print(dict(counter.most_common()))

Running on IDEONE

If you want to disregard space:

from collections import Counter

sentence = 'teste conaz'
counter = Counter()

for word in sentence.split():
    counter.update(word)

# [('t', 2), ('e', 2), ('s', 1), ('c', 1), ('o', 1), ('n', 1), ('a', 1), ('z', 1)]
print(counter.most_common())

# {'t': 2, 'e': 2, 's': 1, 'c': 1, 'o': 1, 'n': 1, 'a': 1, 'z': 1}
print(dict(counter.most_common()))

Running on IDEONE

  • The blank space is missing from the dictionary.

  • @Foci Thanks. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.