'How can I create an input that will loop and create a new list each time?

in case it isn't already obvious im new to python so if the answers could explain like im 5 years old that would be hugely appreirecated.

I'm basically trying to prove to myself that I can apply some of the basic that I have learnt into making a mini-contact book app. I don't want the data to save after the application has closed or anything like that. Just input your name, phone number and the city you live in. Once multiple names are inputted you can input a specific name to have their information printed back to you.

This is what I have so far:

Name = input("enter name here: ")
Number = input("enter phone number here: ")
City = input("enter city here: ")
User = list((Name, Number, City))

This, worked fine for the job of giving python the data. I made another input that made python print the information back to me just to make sure python was doing what I wanted it to:

print("Thank you! \nWould you like me to read your details back to you?")
bck = input("Y / N")
if bck == "Y":
    print(User)
    print("Thank you! Goodbye")
else:
    print("Goodbye!")

The output of this, is the list that the user creates through the three inputs. Which is great! I'm happy that I have managed to make it function so far;

But I want the 'Name' input to be what names the 'User' list. This way, if I ask the user to input a name, that name will be used to find the list and print it. How do I assign the input from Name to ALSO be what the currently named "User" list



Solution 1:[1]

#can be easier to use with a dictionary
#but its just basic
#main list storing all the contacts
Contact=[]

#takes length of contact list,'int' just change input from string to integer 
contact_lenght=int(input('enter lenght for contact'))

print("enter contacts:-")

#using for loop to add contacts
for i in range(0,len(contact_lenght)):
    #contact no.
    print("contact",i+1)

    Name=input('enter name:')
    Number=input('enter number:')
    City=input("enter city:")

    #adding contact to contact list using .append(obj)
    Contact.append((Name,Number,City))

#we can directly take input from user using input()
bck=input("Thank you! \nWould you like me to read your details back to you?[y/n]:")

#checking if user wants to read back
if bck=='y':
    u=input("enter your name:")

    #using for loop to read contacts
    for i in range(0,len(Contact)):

        #if user name is same as contact name then print contact details
        if u==Contact[i][0]:
            print("your number is",Contact[i][1])
            print("your city is",Contact[i][2])

else:

    #if user doesnt want to read back then print thank you
    print("Good bye")

Solution 2:[2]

For this purpose you should use a dictionary. The key of every entry should be the string 'User[0]' that corresponds to the person's name. The contents of every entry should be the list with the information of that user.

I'll give you an example:

# first we need to create an empty dictionary
data = {}

# in your code when you want to store information into
# the dictionary you should do like this
user_name = User[0] # this is a string
data[user_name] = User # the list with the information

If you want to access the information of one person you should do like this:

# user_you_want string with user name you want the information
data[user_you_want]

Also you can remove information with this command:

del data[user_you_want_to_delete]

You can get more information on dictionaries here: https://docs.python.org/3/tutorial/datastructures.html#dictionaries

Solution 3:[3]

You should start by defining a class to support name, phone and city. Once you've done that, everything else is easy.

class Data:
    def __init__(self, name, city, phone):
        self.name = name
        self.city = city
        self.phone = phone
    def __eq__(self, other):
        if isinstance(other, str):
            return self.name == other
        if isinstance(name, type(self)):
            return self.name == other.name and self.city == other.city and self.phone == other.phone
        return False
    def __str__(self):
        return f'Name={self.name}, City={self.city}, Phone={self.phone}'

DataList = []

while (name := input('Name (return to finish): ')):
    city = input('City: ')
    phone = input('Phone: ')
    DataList.append(Data(name, city, phone))

while (name := input('Enter name to search (return to finish): ')):
    try:
        print(DataList[DataList.index(name)])
    except ValueError:
        print('Not found')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 new_reZn
Solution 2 Pedro Rodrigues
Solution 3 Albert Winestein