Appending a dictionary value to a list in python - python

I'm having trouble appending the student dictionary value that coincides with key 'id' to a list. Any help is much appreciated!
students = list();
students.append( {'id':12345, 'first_name':'Alice',
'last_name':'Anderson','assignments':[('assignment_1',0),('assignment_2',2),
('assignment_3',3)]})
students.append({'id':22345, 'first_name':'John',
'last_name':'Sparks','assignments':[('assignment_1',2),('assignment_2',3),
('assignment_3',4)]})
students.append({'id':32345, 'first_name':'Taylor',
'last_name':'Mason','assignments':[('assignment_1',3),('assignment_2',2),
('assignment_3',3)]})
def return_passing(students):
grade_sum = 0
counter = 0
for s in students: #loop thru students
for assignment, grade in s['assignments']:
grade_sum += grade
counter += 1
average = grade_sum / counter
lst = list()
if average >= 2.0:
lst.append((s['id']))
return lst
return_passing(students)
print(return_passing(students))

You have several issues with initializing things at the wrong place, so they get reset. Explanations for those are in the comments:
def return_passing(students):
lst = [] # initialize lst here
for s in students: #loop thru students
grade_sum = 0 # reset these for each student
counter = 0
for assignment, grade in s['assignments']:
grade_sum += grade
counter += 1
# now that we have gone throug all assignments
# compute average
average = float(grade_sum) / counter # convert to float for precision
if average >= 2.0:
lst.append(s['id'])
return lst # return only after you've gone through all students

Related

Python simple loop of averages only returns first item

I wrote a code to calculate an average, but it takes only the first item in the list.
I want to input a list of key=value and it should add all the values and then divide by the total number, so it gives me the average.
def average_price_petrol(**args):
result = 0
total = 0
for key,value in args.items():
result += value
total +=1
return result/total
average_price_petrol(aral = 1.799, bft = 1.629, esso = 1.799, shell = 1.829, jet = 1.719)
In addition to the already mentioned indentation issue for return which causes the function to return on the very first loop iteration, you do not need to iterate over args.items() as you don't care about the keys.
def average_price_petrol(**args):
result = 0
total = 0
for value in args.values():
result += value
total += 1
return result / total
And this can be simplified to:
def average_price_petrol(**args):
return sum(args.values()) / len(args)
You need to indent the code properly.
def average_price_petrol(**args):
result = 0
total = 0
for key,value in args.items():
result += value
total +=1
return result/total
Python uses spaces to determine scopes so your code would loop through the first argument and then return the average before the loop has finished

Dictionary task in Python: Elections

The first line gives the number of entries. Further, each entry contains the name of the candidate and the number of votes cast for him in one of the states. Summarize the results of the elections: for each candidate, determine the number of votes cast for him. Use dictionaries to complete the tasks.
Input:
Number of voting records (integer number), then pairs <> - <>
Output:
Print the solution of the problem.
Example:
Input:
5
McCain 10
McCain 5
Obama 9
Obama 8
McCain 1
Output:
McCain 16
Obama 17
My problem is at the step when I have to sum keys with same names but different values.
My code is:
cand_n = int(input())
count = 0
countd = 0
cand_list = []
cand_f = []
num = []
surname = []
edict = {}
while count < cand_n:
cand = input()
count += 1
cand_f = cand.split(' ')
cand_list.append(cand_f)
for k in cand_list:
for i in k:
if i.isdigit():
num.append(int(i))
else: surname.append(i)
while countd < cand_n:
edict[surname[countd]] = num[countd]
countd += 1
print(edict)
You can add the name and vote to the dictionary directly instead of using one more for() and while().
If the name does not exist in the dictionary, you add the name and vote. If the name exists in the dictionary, increase the vote.
cand_n = int(input())
count = 0
cand_list = []
cand_f = []
edict = {}
while count < cand_n:
cand = input()
count += 1
cand_f = cand.split(' ')
if cand_f[0] in edict:
edict[cand_f[0]] += int(cand_f[1])
else:
edict[cand_f[0]] = int(cand_f[1])
print(edict)

Issues with KeyError: 0

Im having issued where my code keeps saying KeyError: 0, I have searched all over and couldn't find a way to fix this
student_scores = {'0':65.0, '1':54.7}
average_score = 66.0
i = 0
for v in student_scores:
if student_scores[i] >= average_score:
above_avg_check = "{} {}".format(student_names[i], student_scores[i])
above_avg.append(above_avg_check)
print(above_avg_check)
i += 1
I am not sure on what to do, i is both a counter and the key of student_scores, so I can use it in a while loop.
You're checking an integer index while your 0 index is actually a string.
This code compiles for me on repl, just convert your index values to strings before trying to find them
student_scores = {'0':65.0, '1':54.7}
average_score = 66.0
i = 0
for v in student_scores:
if student_scores[str(i)] >= average_score:
above_avg_check = "{} {}".format(student_names[str(i)], student_scores[str(i)])
above_avg.append(above_avg_check)
print(above_avg_check)
i += 1
You can use the .items() method and get the scores in a much more simple way. The you can format your string based on the student and their score within your for loop.
student_scores = {'0': 65.0, '1': 54.7}
average_score = 65.0
i = 0
above_avg = []
for student, score in student_scores.items():
if score >= average_score:
above_average_check = '{}: {}'.format(student, score)
above_avg.append(above_average_check)
print(above_average_check)
i += 1
And here is your output:
0: 65.0
This will get you the output that you are looking for as you iterate through each key and its corresponding value.

Python - Using a created list as a parameter

When I run my code it tells me: Type Error: unorderable types: str() < float(). I can't figure out why it won't let me compare these two numbers. The list I am using is defined, and the numbers in it have been redefined as floats, so I'm not sure what else to do. Any suggestions?
def countGasGuzzlers(list1, list2):
total = 0
CCount = 0
HCount = 0
for line in list1:
if num < 22.0:
total = total + 1
CCount = CCount + 1
for line in list2:
if num < 27.0:
total = total + 1
Hcount = Hcount = 1
print('City Gas Guzzlers: ',CCount)
print('Highway Gas Guzzlers: ',HCount)
print('Total Gas Guzzlers: ',total)
This is my list definition. I'm pretty sure it's fine, but maybe there are some bugs in here as well?
CityFile = open('F://SSC/Spring 2015/CSC 110/PythonCode/Chapter 8/HW 4/carModelData_city','r')
for line in CityFile:
CityData = CityFile.readlines()
for num in CityData:
numCityData = float(num)
CityList = numCityData
HwyFile = open('F://SSC/Spring 2015/CSC 110/PythonCode/Chapter 8/HW 4/carModelData_hwy','r')
for line in HwyFile:
HwyData = HwyFile.readlines()
for num in HwyData:
numHwyData = float(num)
HwyList = numHwyData
I believe you are incorrectly referencing to num instead of line which is the counter variable in your for loops, you either need to use num as the counter variable, or use line in the if condition.
def countGasGuzzlers(list1, list2):
total = 0
CCount = 0
HCount = 0
for line in list1:
if float(line) < 22.0:
total = total + 1
CCount = CCount + 1
for line in list2:
if float(line) < 27.0:
total = total + 1
Hcount = Hcount = 1
print('City Gas Guzzlers: ',CCount)
print('Highway Gas Guzzlers: ',HCount)
print('Total Gas Guzzlers: ',total)
Another issue I see is with the way you are creating the lists . The issue is that you are converting each num in file to float and then storing that directly in list variable, which causes list variable to actually store a float value instead of a list, you need to append each value into list, instead of doing list = num
The code would look like -
CityFile = open('F://SSC/Spring 2015/CSC 110/PythonCode/Chapter 8/HW 4/carModelData_city','r')
for line in CityFile:
CityData = CityFile.readlines()
for num in CityData:
numCityData = float(num)
CityList.append(numCityData)
HwyFile = open('F://SSC/Spring 2015/CSC 110/PythonCode/Chapter 8/HW 4/carModelData_hwy','r')
for line in HwyFile:
HwyData = HwyFile.readlines()
for num in HwyData:
numHwyData = float(num)
HwyList.append(numHwyData)
Please also make sure CityList and HwyList are initialized before this code as lists. Like below -
CityList = []
HwyList = []

summing the dice trials and histogram plot

I am stuck in a code in python which takes in number of dices and number of rolls and returns the sum of numbers obtained. It should also print the histogram of the sum. I am stuck in the first part of the code. Can someone help me fix this? Not sure where i am going wrong. Any help for the second part (returning histogram) would be helpful for me to learn it in python.
from random import choice
def roll(rolls,dice):
d = []
for _ in range(rolls):
d[sum(choice(range(1,7)) for _ in range(dice))] += 1
return(d)
Your problem here is that you can't arbitrarily index into an empty list:
l = []
l[13] += 1 # fails with IndexError
Instead, you could use a defaultdict, which is a special type of dictionary that doesn't mind if a key hasn't been used yet:
from collections import defaultdict
d = defaultdict(int) # default to integer (0)
d[13] += 1 # works fine, adds 1 to the default
or Counter, which is designed for cases like this ("provided to support convenient and rapid tallies") and provides extra handy functions (like most_common(n), to get the n most common entries):
from collections import Counter
c = Counter()
c[13] += 1
To manually use a standard dict to do this, just add a check:
d = {}
if 13 in d: # already there
d[13] += 1 # increment
else: # not already there
d[13] = 1 # create
Try this,
from random import choice
import pylab
def roll( rolls, dice ):
s = list()
for d in range( dice ):
for r in range( rolls ):
s.append( choice( range(1,7) ) )
return s
s = roll( rolls, dice )
sum_of_rolls = sum( s )
# then to plot..
pylab.hist( s )
This should do it
import random
def rolls(N, r): # N=number of dice. r=number of rolls
myDie = [1,2,3,4,5,6]
answer = {}
for _rolling in range(r):
rolls = []
for _die in range(N):
rolls.append(random.choice(myDie))
total = 0
for roll in rolls:
total += roll
if total not in answer:
answer[total] = 0
answer[total] += 1
return answer

Categories

Resources