Dictionary doubt

Asked

Viewed 143 times

-2

How do I count dictionary elements?

datum:

inserir a descrição da imagem aqui

I need to implement a phone account function, which receives a phonebook and returns the amount of registered phone numbers.

If there are repeat phones (the schedule_best example has!), count repetitions (answer 4)

The code I created is not working:

inserir a descrição da imagem aqui

  • or was it something like that? def conta_phones(phonebook): cont = 0 for person in phonebook: for phone in person: if phonebook[person][phone] is not None: cont += Len(person[phone]) Return cont

  • 2

    Please click on [Edit] and put the code as text. Putting it as an image is not ideal, understand the reasons reading the FAQ.

  • But just to advance one of the problems (I didn’t test the code, so I don’t know if it’s the only problem): the key to the dictionaries is "phones" (plural). but vc is trying to access "phone" (singular). I also did not understand why the result should be 4, and only one of the phones is repeated.

  • 1

    Hello Tatiane, new questions about Python code, you are doing an academic work?

  • Reinforcing, puts JSON and python code data with accents , so it is presented correctly, making it easier for Ctrl - c.

2 answers

0

Looks like you want to work with the dictionary keys in the loop for. In this case, use:

for pessoa in agenda.keys():

0

Tatiane, this is a map => reduce. You apply a function to the data, and then you add it all up:

from functools import reduce

def conta_telefones(agenda):

    comprimentos = map(lambda dados:len(dados.get('telefones')), 
                       agenda.values())

    return reduce(lambda total, v: total + v,
                  comprimentos)

Browser other questions tagged

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