How to sort a dictionary list alphabetically and generate new dictionaries with if condition with Python?

Asked

Viewed 172 times

0

Good night,

I have a Python exercise that has stopped me, it is the following:

Read and store in a dictionary the name, age and phone number of your contacts, the key being the name. When typing an empty string for the name, the program stops reading and ends. Display on the screen the data read in alphabetical order by the name of the contacts. A possible solution to sort alphabetically is to use the Sort method. Then store the contacts in two other dictionaries, using the age criterion: under 18 years in one and the largest in another dictionary, eliminating the original. Display on screen the two dictionaries resulting from the separation.

I was able to generate the dictionary and its lists according to the entry and break of the program if the first entry of the name is string vázia.

However, I cannot print the dictionary alphabetically, since if I apply Sort to the name key, it only adjusts it and I apply all the information to the other ones. Also I could not think of a way to make this separation of dictionaries, dividing the contacts that are older than 18 years in one and the minors in another dictionary and eliminating the original.

Could someone give me an idea please?

Code to date:

informations = {'name':[], 'age':[], 'cellphone':[]}

for i in range(3):
  name = str(input('Qual o nome do seu contato? '))
  if name == "":
    print('Programa encerrado...')
    break
  age = int(input('Qual a idade do seu contato? '))
  cellphone = int(input('Qual o número de celular do seu contato? '))
  
  informations['name'].append(name)
  informations['name'].sort()
  informations['age'].append(age)
  informations['cellphone'].append(cellphone)

print('')
print(informations)

1 answer

1


Oops! There is a problem in the design of your program because you are not storing name, age and phone in a dictionary and yes, storing names, ages and phones not related to each other.

I mean, instead of:

informations = {'name':[], 'age':[], 'cellphone':[]}

You should use:

informations = []

With each item in the list you store the contact information:

informations.append({'name': name, 'age':age, 'cellphone':cellphone})

Then it is possible to use the sort() to sort the list:

informations.sort(key=lambda contact: contact["name"])

This part after "key=" is a function that sort() will use to retrieve the value to be used in sorting. And the function lambda takes care to return the name of the contact and just to exemplify:

>>> c = {"name": "José", "age": 10, "cellphone": "9876-5432"}
>>> c = lambda i: i["name"]
>>> a(c)
'José'

This lambda is equivalent to a

def c(i):
    return i["name"]

Only simpler.

Ah, and for more details see Sorting HOW TO python.

And as for separating into two dictionaries, there are several ways but how would you do if they were paper chips? You would look register by register and would make two stacks with who is older, or not 18 years:

greater_than_18, lesser_than_18 = [], []

for contact in information:
    if contact["age"] > 18:
        greater_than_18.append(...)
    else:
        lesser_than_18.append(...)

It is possible to do this in various ways but this is the simplest way.

  • Our show Giovanni, now cleared me very much on this issue, thank you very much for the help

Browser other questions tagged

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