can you help me to flip list to dictionary
shopping_list = raw_input("Enter you Shopping List: ").title().split(',')
i need to flip this list to dictionary
and i dont know how much product the user want to input
This question is a bit ambiguous as you did not provide example input or output. I will assume that you are going to ask the user multiple times to enter in an item and how many they need separated by a comma. If the input changes, then I will edit my answer.
dictionary = {}
item, numberOfItems = raw_input("Enter your Shopping List: ").title().split(',')
dictionary[item] = numberOfItems
This is assuming that no matter what, your input comes in the form of:
banana,3
carrot,7
pack of gum,9
Edit
Since I see what the input is, I can answer this better.
The input string someone will input follows this pattern:
item1,3,item2,7,item3,20,item4,5
So we need to split the input every 2 items.
my_list = raw_input("Enter your Shopping List: ").title().split(',')
composite_list = [my_list[x:x+2] for x in range(0, len(my_list),2)]
This should set composite_list as such.
[[item1,3], [item2,7], [item3,20], [item4,5]]
Now all we need to do is loop through composite_list
for pair in composite_list:
print('({}:{})'.format(pair[0], pair[1]))
The output will now look like:
(item1:3)
Related
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)
Write a program that ask the user to enter an integer representing the number of items to be added to the stock. For these items, the program should then ask for the item barcode number and name, add them to a dictionary and print them.
Why is my code not working as expected?
size=input("Enter size of list")
names=[input()]
code=[int(input())]
for i in size:
print("Enter name and code")
names.append(input())
code.append(int(input()))
dict={names[i]:code[i]}
print(dict)
This a functioning version of your code:
size = input("Enter size of list")
names = []
code = []
for i in range(int(size)):
print("Enter name and code")
names.append(input())
code.append(int(input()))
d = dict(zip(names, code))
print(d)
Among the errors that needed fixing:
Only use input() in your for loop when you need the data.
i needs to cycle through range(int(size)) rather than a string input.
Create the dictionary from your lists at the end via zip.
Do not name variables after classes, e.g. use d instead of dict.
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
Here is what I have so far:
TotalLists=int(input("How many Lists are you making?"))
TotalListsBackup=TotalLists
Lists=[]
while TotalLists>0:
ListName=input("What would you like to call List Number "+str(TotalLists))
Lists.append(ListName)
TotalLists=TotalLists-1
TotalLists=TotalListsBackup-1
while TotalLists>=0:
Lists[TotalLists] #I would like to create actual lists out of the list names at this step but I dont know how...
TotalLists=TotalLists-1
TotalLists=TotalListsBackup-1
print("Here are your Lists: ")
while TotalLists>=0:
print(Lists[TotalLists])
TotalLists=TotalLists-1
I want to be able to:
create a List out of the List Names
The code to be able to make as many lists as the user wants to without a cap
For example, I want to input: Grocery,
The code will create a list Called Grocery
Solutions I have thought of:
Arrays? (I have never used them, I am very new to Python Programming and I dont know too much)
Lists of Lists? (Not sure how to do that. Looked it up, but didn't get a straight answer)
Using Variables, Creating a list with a name like:
List1[]
and have varible called:
List1Name=input("What would you like to call list 1?")
I do not know how to create an infinite number of lists using this way though.
If you have any questions please ask, for I know I am not good at explaining.
It's interesting that you have tagged the question "dictionary" but didn't mention that in your post. Did somebody tell you to use a dictionary? That's exactly what you should be doing, like this (assume TotalLists is already defined):
d = {}
for _ in range(TotalLists): # The same loop you have now
ListName = input("whatever...")
d[ListName] = []
At the end of this you have a dictionary d containing keys that are the user-entered names, and values that are empty lists. The number of dictionary entries is TotalLists. I'm ignoring the possibility that the user will enter the same name twice.
You're solving an XY problem. There's no need to ask for the number of lists in advance. I would recommend using a dictionary:
>>> lists = {}
>>> while 1:
... newlist = input("Name of new list (leave blank to stop)? ")
... if newlist:
... lists[newlist] = []
... while 1:
... newitem = input("Next item? ")
... if newitem:
... lists[newlist].append(newitem)
... else:
... break
... else:
... break
...
Name of new list (leave blank to stop)? groceries
Next item? apples
Next item? bananas
Next item?
Name of new list (leave blank to stop)? books
Next item? the bible
Next item? harry potter
Next item?
Name of new list (leave blank to stop)?
>>> lists
{'groceries': ['apples', 'bananas'], 'books': ['the bible', 'harry potter']}