Printing all dictionary results from For Loop in Python - python

I am trying to print the results from all 3 names that are input, in a dictionary format. Current code below only prints out the last name. The 2 lines commented out (#) are what I was trying to change around to get it to work, clearly not doing it correctly.
def name():
count = 0
while (count < 5):
d = {}
qs = dict(Fname='first name', Lname='last name')
for k,v in qs.items():
d[k] = input('Please enter your {}: '.format(v))
#d['first name'].append(v)
#d['last name'].append(v)
count += 1
print(d)
name()

A few things that I'd change:
append each record (dictionary) to a list of entries.
(optional) Use a for-loop rather than a while as less lines of code.
return the entries list, rather than print it as it is a function so I like to have outputs.
So here's the corrected code:
def name():
entries = []
for count in range(5):
d = {}
qs = dict(Fname='first name', Lname='last name')
for k, v in qs.items():
d[k] = input('Please enter your {}: '.format(v))
entries.append(d)
return entries
print(name())
For testing purpose, I modified it to just except 2 entries, but we can still see that it works:
Please enter your last name: fish
Please enter your first name: bowl
Please enter your last name: cat
Please enter your first name: mat
[{'Lname': 'fish', 'Fname': 'bowl'}, {'Lname': 'cat', 'Fname': 'mat'}]

Hope! you got it right from Martijin Comments, For reference to other adding this code:
def name():
count = 0
listOfDict = [] #creating empty list
for count in range(3):
dict = {}
qs = dict(Fname = 'first name', Lname = 'last name' )
for k,v in qs.items():
d[k] = input('please enter your {}: '.format(v))
listOfDict.append(d) # adding each item to the list.
count += 1
print listOfDict
name()

This should work:
def name():
count = 0
while (count < 5):
d = {}
qs = dict(Fname='first name', Lname='last name')
for k,v in qs.items():
a = input('Please enter your {}: '.format(v))
d[v] = a
count += 1
print(d['first name'],d['last name'])
name()

You can use defaultdict to automatically create lists to store each entered value. The main idea is that you want to append each entered value to a collection of some type (e.g. list).
from collections import defaultdict
number_of_entries = 3
dd = defaultdict(list)
for _ in range(number_of_entries):
for key in ('first name', 'last_name'):
dd[key].append(input('please enter you {}: '.format(key)))
>>> print(dict(dd))
{'first name': ['Adam', 'Milton', 'Irving'],
'last_name': ['Smith', 'Friedman', 'Fisher']}

Related

How do I call a key from my dictionary and print its corresponding values?

I'm having trouble getting user_input to search for keys inside my dictionary, it doesn't return anything at the moment. I have print('bleg') as a placeholder as I test it, but my goal is to have user_input call its corresponding values from the dictionary.
my_file = open('grades.csv','r')
gradescsv = my_file.readlines()
skipheader = 3
records = {}
for i in gradescsv:
cols = i.split(',')
if(skipheader == 0):
students = {}
courses = {}
course1 ={}
course2 = {}
course1['hw1'] = cols[2]
course1['hw2'] = cols[3]
course1['midterm'] = cols[4]
course1['final'] = cols[5]
course2['hw1'] = cols[6]
course2['hw2'] = cols[7]
course2['midterm'] = cols[8]
course2['final'] = cols[9]
courses['Course 1'] = course1
courses['Course 2'] = course2
records[cols[0]+''+cols[1]] = courses
else:
skipheader -= 1
user_input = input('Enter student name: ')
if user_input in records:
print('bleg')

Need help in python dictionaries

This code saves a number of key and value pair from the user but I want to go further and enter keys to be searched in phone book .Can someone tell me what's wrong with my code
phonebook = {}
n = int(input())
for x in range (n):
name , phoneno = input().split()
phonebook[ name ] = int(phoneno)
for y in phonebook:
name = input().split()
if name in phonebook:
print("Found")
else:
print('Not Found')
phonebook = {}
n = int(input())
for x in range (n):
name , phoneno = input().split()
phonebook[ name ] = int(phoneno)
name = input().split()
out = phonebook.get(name,None)
if out == None:
print('Not found')
else:
print('found')
You don't need a loop to check for a key in a dictionary
In name , phoneno = input().split() the .split() needs an argument on what to split it on, so lets say you did thisGuy 69420, if you did .split(' ') space being the argument name & phoneno would both be a list, which at index [0] would be thisGuy and at index[1] would be 69420
Hopefully, that helps :)

Creating an infinite dictionary. It's possible?

I'm trying to define a function that receive infinite values in dictonary, but the the exit is taking only the characters of the last 2 key and value.
Any suggestion?
def infinityInvent():
infinityInvent = []
while True:
keys = input(f'Enter a item (or blank to stop): ')
values = input(f'What the value? ')
if keys == '':
break
infinityInvent = dict(zip(keys, values)) # or infinityInvent = {k: v for k, v in zip(keys, values)}
infinityInvent()
You need to set an item in the dict, not redefine the dict:
def infinityInvent():
infinityInvent = {}
while True:
key = input(f'Enter a item (or blank to stop): ')
if key == '':
break
value = input(f'What the value? ')
infinityInvent[key] = value
return infinityInvent
print(infinityInvent())

Finding the top 10 and converting it from centimeters to inches - Python

I am reading data from file, like listed below, it is a .dat file:
1
Carmella Henderson
24.52
13.5
21.76
2
Christal Piper
14.98
11.01
21.75
3
Erma Park
12.11
13.51
18.18
4
Dorita Griffin
20.05
10.39
21.35
The file itself contains 50 records. From this data I need the person number, name and the first number, like so:
1 #person number
Marlon Holmes #Name
18.86 # First number
13.02 # Second Number
13.36 # Third Number
I already have code to read the data however I unable to get the top 10 results based on the #First number
The #First number in the Top 10 currently is in centimeters but needs to be converted to inches, I am unsure on how to combine the top 10 and conversion into one alongside the reading of the data
Code that reads the data:
with open('veggies_2016.txt', 'r') as f:
count = 0
excess_count = 0
for line in f:
if count < 3:
print(line)
count += 1
elif count == 3 and excess_count < 1:
excess_count += 1
else:
count = 0
excess_count = 0
As mentioned the code reads the file, like so #Person number, #name and #first number, but #first number needs to be converted to inches and then all of the data needs to be sorted to find the top 10
This process will also have to be repeated for #second number and #third number however they are separate in terms of their code from #first number
I have tried to read the data then append to a list and sort it and convert it from that but with no success, any help would be appreciated
Whole code:
from collections import OrderedDict
from operator import itemgetter
import pprint
def menu():
exit = False
while not exit:
print("To enter new competitior data, type new")
print("To view the competition score boards, type Scoreboard")
print("To view the Best Overall Growers Scoreboard, type Podium")
print("To review this years and previous data, type Data review")
print("Type quit to exit the program")
choice = raw_input("Which option would you like?")
if choice == 'new':
new_competitor()
elif choice == 'Scoreboard':
scoreboard_menu()
elif choice == 'Podium':
podium_place()
elif choice == 'Data review':
data_review()
elif choice == 'quit':
print("Goodbye")
raise SystemExit
"""Entering new competitor data: record competitor's name and vegtables lengths"""
def competitor_data():
global competitor_num
l = []
print("How many competitors would you like to enter?")
competitors = raw_input("Number of competitors:")
num_competitors = int(competitors)
for i in range(num_competitors):
name = raw_input("Enter competitor name:")
Cucumber = raw_input("Enter length of Cucumber:")
Carrot = raw_input("Enter length of Carrot:")
Runner_Beans = raw_input("Enter length of Runner Beans:")
l.append(competitor_num)
l.append(name)
l.append(Cucumber)
l.append(Carrot)
l.append(Runner_Beans)
competitor_num += 1
return (l)
def new_competitor():
with open('veggies_2016.txt', 'a') as f:
for item in competitor_data():
f.write("%s\n" %(item))
def scoreboard_menu():
exit = False
print("Which vegetable would you like the scoreboard for?")
vegetable = raw_input("Please type either Cucumber, Carrot or Runner Beans:")
if vegetable == "Cucumber":
Cucumber_Scoreboard()
elif vegetable == "Carrot":
Carrot_Scoreboard()
elif vegetable == "Runner Beans":
Runner_Beans_Scoreboard()
def Cucumber_Scoreboard():
exit = True
print("Which year would you like the Scoreboard from?")
scoreboard = raw_input("Please type a year:")
if scoreboard == "2015":
cucumber_veg_2015()
elif scoreboard == "2014":
cucumber_veg_2014()
elif scoreboard == "2016":
cucumber_veg_2016()
def cucumber_veg_2016(cm):
return float(cm) / 2.54
names = OrderedDict([('Competitor Number', int),
('Competitor Name', str),
('Cucumber', cucumber_veg_2016),
('Carrot', float),
('Runner Bean', float)])
data = []
with open('veggies_2016.txt') as fobj:
while True:
item = {}
try:
for name, func in names.items():
item[name] = func(next(fobj).strip())
data.append(item)
except StopIteration:
break
pprint.pprint(sorted(data, key=itemgetter('Cucumber'))[:10])
Solution
Reading the data into a list of dictionaries would work:
from collections import OrderedDict
from operator import itemgetter
import pprint
def to_inch(cm):
return float(cm) / 2.54
names = OrderedDict([('person_number', int),
('name', str),
('first', to_inch),
('second', float),
('third', float)])
data = []
with open('veggies_2016.txt') as fobj:
while True:
item = {}
try:
for name, func in names.items():
item[name] = func(next(fobj).strip())
data.append(item)
except StopIteration:
break
pprint.pprint(sorted(data, key=itemgetter('first'))[:10])
Output:
[{'first': 4.76771653543307,
'name': 'Erma Park',
'person_number': 3,
'second': 13.51,
'third': 18.18},
{'first': 5.897637795275591,
'name': 'Christal Piper',
'person_number': 2,
'second': 11.01,
'third': 21.75},
{'first': 7.893700787401575,
'name': 'Dorita Griffin',
'person_number': 4,
'second': 10.39,
'third': 21.35},
{'first': 9.653543307086613,
'name': 'Carmella Henderson',
'person_number': 1,
'second': 13.5,
'third': 21.76}]
In Steps
This helper function converts centimeters into inches:
def to_inch(cm):
return float(cm) / 2.54
We use an ordered dictionary to hold the names for the different items we want to read in order. The value is a function that we use to convert the read value for each item:
names = OrderedDict([('person_number', int),
('name', str),
('first', to_inch),
('second', float),
('third', float)])
We start with an empty list:
data = []
And open our file:
with open('veggies_2016.txt') as fobj:
We do something without a defined end and create a new dictionary item each time:
while True:
item = {}
We try to read from the file until it is finished, i.e. until we get a
StopIteration exception:
try:
for name, func in names.items():
item[name] = func(next(fobj).strip())
data.append(item)
except StopIteration:
break
We go through the keys and values of our order dictionary names and call each
value, i.e. the function func() on the next line we retrieve with next().
This converts the entry into the desired datatype and does the cm-inch conversion for first. After reading all items for one person, we append the dictionary to the list data.
Finally, we sort by the key first and print out the 10 to entries
(my example file has less than 10 entries):
pprint.pprint(sorted(data, key=itemgetter('first'))[:10])
Integration with your code:
You need to put the code into the function podium_place():
def cucumber_veg_2016(cm):
return float(cm) / 2.54
def podium_place():
names = OrderedDict([('Competitor Number', int),
('Competitor Name', str),
('Cucumber', cucumber_veg_2016),
('Carrot', float),
('Runner Bean', float)])
data = []
with open('veggies_2016.txt') as fobj:
while True:
item = OrderedDict()
try:
for name, func in names.items():
item[name] = func(next(fobj).strip())
data.append(item)
except StopIteration:
break
sorted_data = sorted(data, key=itemgetter('Cucumber'), reverse=True)
for entry in sorted_data[:10]:
for key, value in entry.items():
print key, value
print
menu()
At the end you need to call menu(). Also, if top mean largest first, you need sort reverse (see above).
I would read them as a record at a time. You can put that functionality in a function that you call several times with the same file. It can return a None when you reach the end of the file. It will return a tuple with all values for a given record (including conversions). You can then use sorted to sort the list of records using any one of the values from each record.
def read_record(fid):
id = fid.readline()
# At the end of the file
if id is None:
return None
name = fid.readline()
# Perform the conversion
number1_inches = float(fid.readline()) / 2.54
number2 = float(fid.readline())
number3 = float(fid.readline())
return (id, name, number1_inches, number2, number3)
with open('filename.txt', 'r') as fid:
records = list()
while True
new_record = read_record(fid)
# Stop if we hit the end of the file
if new_record is None:
break
records.append(new_record)
# Now sort the records based on the value of number1
records = sorted(records, key=lambda x: x[2])

Change prompt to user with each loop pass

How can I create a loop that prompts for a list of items, with the prompt changing each time.
For example "Input your first item" then "Input your second item" etc... (or 1st, 2nd)
I need to add all of the items to an array:
items = []
for i in range(5):
item = input("Input your first thing: ")
items.append(item)
print (items)
Use a list of prompts:
prompts = ('first', 'second', 'third', 'fourth', 'fifth')
items = []
for prompt in prompts:
item = input("Input your {} thing: ".format(prompt))
items.append(item)
Slightly altering your code:
names = {1: "first", 2: "second", 3: "third" # and so on...
}
items = []
for i in range(5):
item = input("Input your {} thing: ".format(names[i+1])
items.append(item)
print(items)
Or a more general version:
def getordinal(n):
if str(n)[-2:] in ("11","12","13"):
return "{}th".format(n)
elif str(n)[-1] == "1":
return "{}st".format(n)
elif str(n)[-1] == "2":
return "{}nd".format(n)
elif str(n)[-1] == "3":
return "{}rd".format(n)
else:
return "{}th".format(n)
Or a more compact definition:
def getord(n):
s=str(n)
return s+("th" if s[-2:] in ("11","12","13") else ((["st","nd","rd"]+
["th" for i in range(7)])
[int(s[-1])-1]))
Why not use string formatting? Something along the lines of
>>> for i in range(5):
items.append(input("Enter item at position {}: ".format(i)))
from collections import OrderedDict
items = OrderedDict.fromkeys(['first', 'second', 'third', 'fourth', 'fifth'])
for item in items:
items[item] = raw_input("Input your {} item: ".format(item))
print items
Output:
Input your first item: foo
Input your second item: bar
Input your third item: baz
Input your fourth item: python
Input your fifth item: rocks
OrderedDict([('first', 'foo'), ('second', 'bar'), ('third', 'baz'), ('fourth', 'python'), ('fifth', 'rocks')])

Categories