I'm currently stuck with this output of a nested list when trying to append the list as the definition of my dictionary.
I know this is probably more code than I should include, but I figured it's helpful to show more than less.
class Account:
accountInfo = {} #ex. ID : 5FE19C (hexadecimal ID's)
def __init__(self):
choice = raw_input("Would you like to login or signup?\n")
if choice.lower() == "login":
self.login()
elif choice.lower() == "signup":
print "Great! Fill in the following."
self.signup()
else:
self.__init__()
def signup(self):
import random
accountID = '%010x' % random.randrange(16**10) # 10 digit hexadecimal ID generator
personalInfo = []
self.accountInfo[accountID] = []
firstName = raw_input("First Name: ")
lastName = raw_input("Last Name: ")
email = raw_input("E-Mail: ")
password = raw_input("Password: ")
birthdate = raw_input("DOB (DD/MM/YYYY): ")
alias = raw_input("Username/Alias: ")
personalInfo.append(firstName)
personalInfo.append(lastName)
personalInfo.append(email)
personalInfo.append(password)
personalInfo.append(birthdate)
personalInfo.append(alias)
for i in range(1):
self.accountInfo[accountID].append(personalInfo)
#creates an unwanted nested list, but the output is correct
print self.accountInfo
I don't understand why I'm getting the output of a nested list in my dictionary. The contents of the dictionary are correct, but it's just that unwanted and unnecessary nested list.
output:
>>> {'6de7bcf201': [['firstName', 'lastName', 'email', 'password', 'birthdate', 'alias']]}
personalInfo = [] # PersonalInfo is a list
# skipped
self.accountInfo[accountID].append(personalInfo) # add list to the list
This is similar to
main = []
p_info = []
main.append(p_info) # result would be main = [[]]
If you want to have just a dict inside list, change personalInfo to {}
that would requare to change personalInfo.append to personalInfo[x] = y
I think this is pretty straight forward:
personalInfo is a list. You append items to it and get something like [..,..,..]. You initiate the value of self.accountInfo[accountID] also as a list. Then you append your first list to the second list, giving you a list of lists.
Instead of self.accountInfo[accountID].append(personalInfo) try self.accountInfo[accountID] = personalInfo
Welcome! A couple of things:
Imports should generally be at the top of a file. For your signup
function, the import random should be at the top.
Your __init__ shouldn't be called again on a class. __init__ is considered the "constructor" of the class - as such it should generally be called once. Consider putting your raw_input section in another function and call that twice.
Print is a function, not a statement (your last line)
To answer your question, you have a nested list because you are making two lists. You're first building up personalInfo and then appending that item to the empty list you made for accountInfo you can have a single-level list if you just set self.accountInfo[accountID] =personalInfo`.
personalInfo is a list and self.accountInfo[accountID] is another list.
With self.accountInfo[accountID].append(personalInfo) you are injecting one inside the other.
You can do self.accountInfo[accountID] = personalInfo
And what's the point of for i in range(1)? It's not looping at all!
I can't test right now but:.
Replace self.accountInfo[accountID] = [] with self.accountInfo[accountID] = personalInfo. And delete for i in range(1): self.accountInfo[accountID].append(personalInfo)
Related
I am using python 3.x, I have the following problem, using the keyboard the user enters certain data and fills N lists to create a contact list, then in a list I collect all the data of the lists, I need to modify the data of each list, (I already have it, I modify the data of a list with a specific value using a for) Example, Names list, I modify Andrew's name, but in the Contacts list, there is all Andrew's information (phone, mail, etc), but I just need to modify in the Contacts list, the value of Andrew
I have all this list:
names = []
surnames = []
phones = []
emails = []
addresses = []
ages = []
salaries = []
genres = []
contacts = []
# and use the append to add the data into the contacts list
contacts.append ([names, surnames, phone numbers, emails, addresses, ages, salaries, genders])
Then I update the info of one contact
search = input(Fore.LIGHTBLUE_EX + "Type the name of the contact you want update: ")
for i in range(len(names)):
if (names[i] == search):
try:
names[i] = input(Fore.MAGENTA + "Type the New name: ")
names[i] = nombres[i].replace(" ", "")
if names[i].isalpha() == True:
print(Fore.GREEN + "Already saved, congrats.")
pause= input(Fore.LIGHTGREEN_EX + "Press enter to exit")
But I dont know how to update the name in the List of contacts.
When you call contacts.append(), you add a list of lists to a list, so your contacts list will look something like this:
contacts = [[[names[0], names[1], ...], [...], [...]]]
It's unnecessary to have a list of one item nested in another list, so I would just call contacts.append() and pass each list (names, surnames, etc.) to the method, which allows for easier indexing.
Since the list names would be the first item in the list contacts (contacts[0]), you could do one of two things (there may be more, but these are off the top of my head):
Reassign the specific index to a new value, using nested-list indexing (contacts[0][0] = "updated name" would update the first item of the names list to "update name")
Reassign the entire nested list to a new list (contacts[0] = new_name_list would reassign contacts[0], formerly the names list, to new_name_list)
On a side note: In this case, I would recommend dictionaries over lists, as it will be easier to keep track of what is being reassigned/modified.
contacts = {
"names": names,
"surnames": surnames,
...
}
Doing this will make it more clear which list your are referring to; contacts[0] doesn't give much information, but contacts["names"] informs readers that you are referring to the names list. This is solely for cleaner code; there isn't much difference in functionality.
What my script is doing now is adding elements to a list. For example, if the user types "JO", I will add "John" to the list. What I want to do now is that, if the user types "2 JO", I add two elements to the list: "John" and "John".
This is how the database looks like now:
Sample database copy.png
This is the code now:
import pandas
data = pandas.read_excel("Sample database copy.xlsx")
name = dict(zip(data["Abbreviation"],data["Name"]))
list1 = []
incoming_msg = input(Please type what you want to add: )
list1.append(name[incoming_msg])
I need to do it all from the same input, I cannot ask separately for quantity and abbreviation. I wanted to know if there is any library that can do this somehow easily because I am a beginner coder. If there is no library but you have any idea how I could solve it, it would be awesome as well.
Thank you so much in advance!
you can use string.split() to split the string by space into a list then use the first element to multiply a list that contains the value from the dictionary and increment it to the result list. see the code
name = dict(zip(data["Abbreviation"],data["Name"]))
list1 = []
incoming_msg = input('Please type what you want to add: ')
incoming_msg = incoming_msg.split() # split the string by space
if len(incoming_msg) == 2: # if there are two elements in the list (number and name)
list1 += [name[incoming_msg[1]]] * int(incoming_msg[0])
else:
list1.append(name[incoming_msg[0]])
I'm trying to create a friend dictionary in which I can add a friend and put there his info.
I want to use the friend's name as the key, two numbers, two emails and information about where he lives.
My problem is that my program crashes when asking for the numbers and for the emails, I dont know what i did wrong.
I used the append, function because the numbers of each friend are saved in a list. I dont want a new program I want to repair mine so I can understand why it's failing.
The other thing I'm trying to do is to not print the empty dictionary that im creating at the end, its a list with dictionaris in it (each friend is a dictionary), so i guess i should say to print the list from the position 1 to the end but i guess there is a better way, here I post my code, the error is when i ask for the first and second phone and mail.
def add_contact(friends):
contact = {}
contact["name"]=input("name: ")
for i in range(2):
contact["phone"][i]=input("phone: ") #Here it crashes
for i in range(2):
contact["mail"][i]=input("mail: ") #Here too
contact["street"]=input("street: ")
contact["housenum"]=input("housenum: ")
contact["cp"]=input("cp: ")
contact["city"]=input("city: ")
friends.append(contact)
friends = [{"name":[{"telf":[0]*2},{"mail":[0]*2},
{"street":"","housenum":"","cp":"", "city":""}]}] #This is the list im creating to fill it with friends information, the first dictionary in the list is an empty dictionary which i dont want to print.
add_contact(friends)
print(friends)
You need to create a list for the phone and email, then append to it:
def add_contact(friends):
contact = {}
contact["name"]=input("name: ")
contact["phone"] = []
contact["mail"] = []
for i in range(2):
contact["phone"].append(input("phone: "))
for i in range(2):
contact["mail"].append(input("mail: "))
contact["street"]=input("street: ")
contact["housenum"]=input("housenum: ")
contact["cp"]=input("cp: ")
contact["city"]=input("city: ")
friends.append(contact)
friends = [{"name":[{"telf":[0]*2},{"mail":[0]*2},
{"street":"","housenum":"","cp":"", "city":""}]}] #This is the list im creating to fill it with friends information, the first dictionary in the list is an empty dictionary which i dont want to print.
add_contact(friends)
print(friends)
The problem with your solution is that you try to add value to something which is not present.
When you do contact["phone"]. This creates a key inside dictionary contact. {"Phone":}
But the problem is you do contact["phone"][i]. So ith element is searched in this key. Which is not present. Hence you get error. So you first need to add list to this dictionary. Then only you can add multiple numbers
def add_contact(friends):
contact = {}
contact["name"]=input("name: ")
contact["phone"] = []
contact["mail"] = []
for i in range(2):
contact["phone"].append(input("phone: "))
for i in range(2):
contact["mail"].append(input("mail: "))
contact["street"]=input("street: ")
contact["housenum"]=input("housenum: ")
contact["cp"]=input("cp: ")
contact["city"]=input("city: ")
friends.append(contact)
friends = [{"name":[{"telf":[0]*2},{"mail":[0]*2},
{"street":"","housenum":"","cp":"", "city":""}]}] #This is the list im creating to fill it with friends information, the first dictionary in the list is an empty dictionary which i dont want to print.
add_contact(friends)
print(friends)
How would I go about deleting one of these students from a list of tuples? I'm quite confused on this part and not sure where to start. Could anyone help point me in the correct direction?
select=True
data=[]
while select:
print ("""
student Database (student records:)
a. Delete a student from the database
""" )
select=input("What would you like to do? ")
if select == "1":
print("Add a new student")
student = input ("Enter studenbt:")
grades = input ("Enter grade:")
entermark = float (input ("enter mark:"))
fulltime = input ("Is the student full-time? Yes/No:")
data.append((student, grades, entermark, ))
print ("The student you have entered is:",data)
elif select == "a":
delete = input("student do delete?")
Create a dict from your data instead of list. Then you can simply delete the item you want with data.pop(key) in a constant time.
data = {}
# this is how you add data
data['studentName1'] = (10,20)
data['studentName2'] = (32,42)
# this is how you remove data
data.pop('studentName1')
EDIT: I think that #sudomakeinstall2's suggestion of using a dictionary to store your data instead of a list is a good one. If you simply must use a list, then my answer below should help with that.
You can remove an element of a list if you know its index by using the pop() method.
For example:
>>> data.pop(5)
Will remove the 5th element.
In your case, you will want to find the index for the student you want to remove, then use pop() to remove it.
For example you could find the student by iterating through your list like this:
delete = input("Which employee would you like to delete from the database?")
for index, row in enumerate(data):
if row[0] == delete:
data.pop(index)
break
So, I made a dictionary, called groupA, that i want to hold names and multiple scores. The scores come from a variable called count, which is dependent on a quiz from another part of my code. My code adds multiple values to one key, but i want them all in one list, which isn't happening for whatever reason. This is my code:
name = input("What is your name? ")
while name.isdigit():
print ("That's not a name.")
name = input("What is your name? ")
group = input("Which group are you in; A, B or C: ")
if group == "A":
if name in groupA:
groupA = pickle.load(open("groupA.p", "rb"))
score = [count]
groupA[name].append(score)
numberofvalues = len(score)
if numberofvalues > 3:
print("Deleting oldest score.")
score.pop(1)
print(score)
pickle.dump(groupA, open("groupA.p", "wb"))
else:
score = [count]
groupA[name] = [score]
pickle.dump(groupA, open("groupA.p", "wb"))
i want this part of the code to either add to the values in the list, and if there are more than three values in the list, delete the first, then if there isn't an entry for the dictionary with that name; create an entry, but it's not doing this. can someone please help? thank you!
What you are currently doing is equivalent to:
groupA[name].append([count]) # this appends a list to the list
Do it this way
groupA[name].append(count) # count must be single value
And in the else part
groupA[name] = [count] # creating new single-element list
Also, len(scores) will always be 1. Replace it with this:
numberofvalues = len(groupA[name])