Write a Python program that will take N names from the user. Create a dictionary from the N names that will hold First_name, Middle_name, and Last_name in separate keys. The inputs will take N at first and then take N names. You can assume that the names will contain less than or equal to 3 words.
Sample Input:
4
Zubayer Ahmed
Sadia Nur Amin
Mehedi Hasan Shawon
Nafis
Sample Output:
{ "Fname" : [“Zubayer”, “Sadia”, “Mehedi”, “Nafis”] , "Mname" : [“Nur”, “Hasan”], "Lname" : [“Ahmed”, “Amin”, “Shawon”] }
This problem requires you to first find the number of names needed, this can be done using a simple input() call.
numNames = int(input("> "))
we can also prepare the dictionary like so
nameDict = {"Fname":[],"Mname":[],"Lname":[]}
Then we need to iterate depending on the number the user has entered
for i in range(numNames):
During each iteration of the above for loop, you need to ask the user for a name, then split it into a list of each names names = input("name {i+1} > ").split(" ")
You can then add them to the dictionary as the problem requires using basic selection
if len(names) >= 1:
nameDict["Fname"].append(names[0])
if len(names) == 2:
nameDict["Lname"].append(names[1])
elif len(names) == 3:
nameDict["Mname"].append(names[1])
nameDict["Lname"].append(names[2])
This solution could be made more efficient if you can find a better way to sort the names into the dictionary.
Although StackOverflow isn't for your entire problems, more so questions about specific areas. Next time have a go at the problem and post if you get suck with details about your attempt.
But anyway, here is my full solution
numNames = int(input('names >'))
nameDict = {'Fname':[],'Mname':[],'Lname':[]}
for i in range(numNames):
names = input(f'name {i+1} > ').split(' ')
if len(names) >= 1:
nameDict["Fname"].append(names[0])
if len(names) == 2:
nameDict["Lname"].append(names[1])
elif len(names) == 3:
nameDict["Mname"].append(names[1])
nameDict["Lname"].append(names[2])
print(nameDict)
Here's my solution:
number_of_entries = int(input("How many entries would you like? "))
first_names = []
middle_names = []
last_names = []
i = 0
while i < number_of_entries:
full_name = input(": ")
names_array = full_name.split(' ')
if len(names_array) >= 1:
first_names.append(names_array[0])
if len(names_array) >= 2:
middle_names.append(names_array[1])
if len(names_array) >= 3:
last_names.append(names_array[2])
i += 1
names_dictionary = { "Fname" : first_names, "Mname" : middle_names, "Lname" : last_names}
print(names_dictionary)
It works by storing every category of name into an array first then adding that to the dictionary in the end.
In this homework, you must handle the initial 4 and read correctly the following input lines.
After that you will have a list of names, I think the best approach is the following
from itertools import zip_longest
names = ["Zubayer Ahmed","Sadia Nur Amin","Mehedi Hasan Shawon","Nafis"]
# split into single words
names = [x.split() for x in names]
# do a zip of the triads and remove None values
filtered = [ list(filter(None,_)) for _ in zip_longest(*names)]
#do the dict:
dict(zip( ("Fname","Mname", "Lname"), filtered))
the output:
{'Fname': ['Zubayer', 'Sadia', 'Mehedi', 'Nafis'],
'Mname': ['Ahmed', 'Nur', 'Hasan'],
'Lname': ['Amin', 'Shawon']}
Related
This is my sample database:
In my script now, I am adding elements to the list with the following code:
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: ')
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]])
So now if type "2 JO" my list will have two new elements "John" and "John".
Now I want to do exactly the same but for eliminating objects of a list. I tried to replace the current operator "+=" for "-=" but surprisingly it is not working. Any ideas on how I could solve this?
PS. I need to do it all out of the same input. I cannot ask separately for key and quantity. I want to make a replication of the above code but for removing the objects.
You could use list.remove():
Remove the first item from the list whose value is equal to x. It
raises a ValueError if there is no such item.
import pandas as pd
data = pd.read_excel("Sample database copy.xlsx")
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]])
print('\n'.join(list1))
incoming_msg = input('Please type what you want to delete: ')
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)
num_to_remove = int(incoming_msg[0])
while name[incoming_msg[1]] in list1 and num_to_remove > 0:
list1.remove(name[incoming_msg[1]])
num_to_remove -= 1
else:
if name[incoming_msg[0]] in list1:
list1.remove(name[incoming_msg[0]])
print('\n'.join(list1))
Example Usage:
Please type what you want to add: 4 JO
John
John
John
John
Please type what you want to delete: 2 JO
John
John
I’m using Python IDE 3. My goal is this: If I have a string of text, ‘ABCDEFGHIJKL’, I want to sort it into groups, like three groups (‘ADGJ’,’BEHK’,’CFIL’). I require input for this, but the prompts aren’t showing up and I can’t type in input. Here’s my code:
#data
code_text = input('Text: ').lower()
code_skip = int(input('Shift length: '))
code_list = []
#function
def countSkip(text, shift, listt):
i = 0
group = 1
if group <= shift:
for e in text:
#make sure the set starts at the right place
if e.index()+1 < group:
pass
elif shift != 0:
if i = shift:
listt.append(e)
i = 0
i += 1
else:
listt.append(e)
group += 1
Calling the function
countSkip(code_text, code_shift, code_list)
There's a few things stopping your code from working that people have pointed out in the comments. Instead of trying to dissect your code and get that to work, I wrote a much more concise function that will get you the results you're after
def text_splitter(input_text, set_length):
num_sets = int(len(input_text)/set_length)
split_text = ["".join([input_text[(n * num_sets) + m] for n in range(set_length)]) for m in range(num_sets)]
return split_text
text_to_split = input('Text: ').lower()
len_set = int(input('Set Length: '))
text_list = text_splitter(text_to_split, len_set)
Sorry I was struggling to name the variables in an effective manner but the function above uses a list expression to get you the results you need. Keep in mind that if you use say a 7 letter string and ask for sets of length 2, the last letter won't be appended. However this shouldn't be too hard to check and correct. For example you could add this code to the function or around the initial input for the set length:
while len(input_text) % set_length != 0:
set_length = int(input("The text is length " + str(len(input_text)) + " please enter a different set length: "))
I'm new to python. I am trying to make a generator that requires 3 letters from an input. I need it to only accept 3 letters no more no less. The if len i put does not work
import random
usernames = int(input("How Many Usernames Are To Be Generated?"))
names = []
for item in range(0,usernames):
names.append(input("What Is The First Three Letters of The Pupils Name?"))
if len(names) == 3:
suffixes = ["ing", "end", "axe", "gex", "goh"]
for name in names:
final = name + random.choice(suffixes)
print(final)
else (names):
print("Error! Must Be 3 Characters")
else requires no condition
import random
usernames = int(input("How Many Usernames Are To Be Generated?"))
names = []
for item in range(0,usernames):
names.append(input("What Is The First Three Letters of The Pupils Name?"))
if len(names) == 3:
suffixes = ["ing", "end", "axe", "gex", "goh"]
for name in names:
final = name + random.choice(suffixes)
print(final)
else :
print("Error! Must Be 3 Characters")
Why is names a list?
You have an empty list, name = [] .
Then you add one item to it .
names.append(input("What ..
This is why it fails, because the len of names is 1.
Either get rid of the list or check the len of the first item .
if len(names[0]) == 3
For homework I have been set the following:
Build a dictionary with the names from myEmployees list as
keys and assign each employee a salary of 10 000 (as value). Loop over the dictionary
and increase the salary of employees which names have more than four
letters with 1000 * length of their name. Print the dictionary contents before
and after the increase.
I can't figure out how to do it.
This is what I've come up with so far.
employeeDict = {"John":'10,000', "Daren":"10,000", "Graham":"10,000", "Steve":"10,000", "Adren":"10,000"}
say = 'Before increase'
print say
print employeeDict
say1 = 'After increase'
print say1
for x in employeeDict:
x = len(employeeDict)
if x > 5:
print employeeDict[x]
First, change the values to integers/floats.
employeeDict = {"John":10000, "Daren":10000, "Graham":10000, "Steve":10000, "Adren":10000}
After doing this, as you know, you need to loop over the items in the dict.
for x in employeeDict:
x = len(employeeDict)
if x > 5:
print employeeDict[x]
In the code above, your "x" will be the employee name. And as you know, to asign a value to a key in dict, you have to use dict[key] = value, so try to do it in the if x > 5: block statement. Im not trying to give you the full answer, but to push you in to the right direction.
You have some indentation problems, clearly, but the main problems are that you are taking the length of the dictionary (getting the number of keys) not taking the length of the key. You also have some bad logic.
employeeDict = {"John":'10,000', "Daren":"10,000", "Graham":"10,000", "Steve":"10,000", "Adren":"10,000"}
say = 'Before increase'
print say
print employeeDict
say1 = 'After increase'
print say1
for x in employeeDict:
length = len(employeeDict) # <---- indent this
if length >= 5: # <--- greater than 4
# convert string to number, add money, convert back to string
employeeDict[x] = str(int(employeeDict[x]) + 1000 * (length))
print employeeDict[x]
This should give you what your looking for.
employeeDict = {"John":10000, "Daren":10000, "Graham":10000, "Steve":10000, "Adren":10000}
print "Before increase"
print employeeDict
for name, salary in employeeDict.items():
if len(name) > 4:
employeeDict[name] = salary + len(name) * 1000
print "After increase"
print employeeDict
You had a few problems in your version.
Your idention for your for-loop was not correct
You were getting the length of the dictionary and not the length of the keys in the dictionary.
You should make the values in your dictionary floats/integers.
Also note, I believe your homework said if the name was longer than four characters. So i used 4 instead of five.
Give this a try and analyse it :
employees = {"John":10000, "Daren":10000, "Graham":10000}
for name in employees:
if len(name) > 5:
employees[name] += 1000 * len(name)
If you have to stick with the string values you can do this :
employees = {"John":"10000", "Daren":"10000", "Graham":"10000"}
for name in employees:
if len(name) > 5:
employees[name] = str(int(employees[name]) + 1000 * len(name))
This is my code and I need to work out the average score for each student but this part of the code is incorrect.It is the part with the stars that I need to fix
while choice == 'av'.lower():
if schClass == '1':
schClass = open("scores1.txt", 'r')
li = open("scores1.txt", 'r')
data = li.read().splitlines()
for li in data:
name = li.split(":")[0]
score = li.split(":")[1]
**if name not in diction1:
diction1[name] = score
elif name in diction1:
diction1[name] = int(score) + diction1[name]**
How does the file look like?
A: 10
B: 10
A: 20
B: 12
or
A: 10 20
B: 10 12
This solution works with both formats.
First, build a dict of lists with all scores:
all_scores = {}
while choice == 'av':
if schClass == '1':
with open("scores1.txt", 'r') as f:
for line in f:
name, scores = li.split(':', 1)
name_scores = all_scores.setdefault(name, [])
for score in scores.split():
name_scores.append(int(score))
Then calculate the average (convert to sum to float in order to get exact average):
averages = {name: float(sum(scores)) / len(scores)
for name, scores in all_scores.iteritems()}
Your question is unclear; in other words, what do you mean with adding more than one integer to a dictionary key? This part is confusing because your code
diction1[name] = int(score) + diction1[name]**
seems to imply you'd like to add a string (score) to an integer (int(score)), which is impossible. If it's to add them side by side in a list so that, given a score of '4', the result is ['4', 4], then all you have to do is change the last few lines to this.
if name not in diction1:
diction1[name] = [score, int(score)]
Also, eumiro's other changes to your code are good advice, so keep them in mind and read the docs if you're unsure of how any of it works.
Make diction1 hold a list.
if name not in diction1:
diction1[name] = [score]
else:
diction1[name].append(int(score))