I want to create a dict like this from input in python - python

all the contents must be inserted from the input
graph={
'A':{'B':3,'C':4},
'B':{'A':3,'C':5},
'C':{'B':5,'D':'1'},
'D':{'C':1},
}

Take the input in JSON format and then you can easily use json.loads to convert it to a dictionary.
>>> import json
>>> graph = json.loads(input("Enter graph as JSON: "))
Enter graph as JSON: {"A":{"B":3,"C":4},"B":{"A":3,"C":5},"C":{"B":5,"D":"1"},"D":{"C":1}}
>>> import pprint
>>> pprint.pprint(graph)
{'A': {'B': 3, 'C': 4},
'B': {'A': 3, 'C': 5},
'C': {'B': 5, 'D': '1'},
'D': {'C': 1}}

record_to_insert = int(input("num of record to insert :: "))
dic = {}
for i in range(record_to_insert):
print("")
key_name = input("parent key name :: ")
dic[key_name] = {}
print("Enter how many number of key,value pairs you want for key :: ",
key_name)
num_of_child_keyvalues_to_insert = int(input(""))
for k in range(num_of_child_keyvalues_to_insert):
key = input("child key name :: ")
value = input("Value name :: ")
dic[key_name][key] = value
print(dic)

def make_dict():
d = {}
while True:
key = input("Enter the key of dict or stay blank to finish adding key to this level of dict: ")
if key == "": # just stay blank to out from func
break
ch = input(f"Do you wanna to create nested dict for the key{key}? [y / <Press Enter for No>] ")
if ch == "y":
value = make_dict() # use recursion
else:
value = input(f"Enter the value for the key {key}: ")
d[key] = value
return d
print(make_dict())
link to screenshot

Related

Python: JSON, Problem with list of dictionaries, certain value into my dictionary

So, I have been thinking of this for a long time now, but can't seem to get it right. So I have to use a JSON file to make a dictionary where I get the keys: 'userIds' and the value 'completed' tasks in a dictionary. The best I got was the answer: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 90}, with this code under:
import requests
response1 = requests.get("https://jsonplaceholder.typicode.com/todos")
data1 = response1.json()
dict1 = {}
keys = []
values = []
for user in data1:
if user not in keys or values:
keys.append(user['userId'])
values.append(0)
for key, value in zip(keys, values):
dict1[key] = value
for user in data1:
if user['completed'] == True:
dict1[key] += 1
print(dict1)
but I feel like this next code would be closer, but I can't figure out how to get it to work
import requests
response1 = requests.get("https://jsonplaceholder.typicode.com/todos")
data1 = response1.json()
dict1 = {}
keys = []
values = []
for user in data1:
if user not in keys or values:
keys.append(user['userId'])
values.append(0)
for key, value in zip(keys, values):
dict1[key] = value
for key, value in data1.items():
if user['completed'] == True:
dict1[key].update += 1
print(dict1)
After this, the output is just
" line 24, in
for key, value in data1.items():
AttributeError: 'list' object has no attribute 'items'",
And I do get why, I don't jsut know how to continue from here.
Would really appreciate anyones help, with this obnoxious task.
can u try this ?
import requests
response1 = requests.get("https://jsonplaceholder.typicode.com/todos")
data1 = response1.json()
dict1 = {}
keys = []
values = []
for user in data1:
if user not in keys or values:
keys.append(user['userId'])
values.append(0)
for key, value in zip(keys, values):
dict1[key] = value
print(data1)
for x in data1:
for key, value in x.items():
if key =="completed" :
if value == True:
dict1[x["userId"]] += 1
print(dict1)
Try with this approach:
import json
import requests
response1 = requests.get("https://jsonplaceholder.typicode.com/todos")
data1 = response1.json()
dict1 = {}
for user in data1:
uid = user['userId']
if user['completed']:
dict1[uid] = dict1.get(uid, 0) + 1
elif uid not in dict1:
dict1[uid] = 0
print(dict1)
print(json.dumps(dict1, indent=2))
If needed, you can also simplify the above logic using defaultdict, and leverage the fact that bool is a subclass of int:
from collections import defaultdict
dict1 = defaultdict(int)
for user in data1:
dict1[user['userId']] += user['completed']
Output:
{1: 11, 2: 8, 3: 7, 4: 6, 5: 12, 6: 6, 7: 9, 8: 11, 9: 8, 10: 12}
{
"1": 11,
"2": 8,
"3": 7,
"4": 6,
"5": 12,
"6": 6,
"7": 9,
"8": 11,
"9": 8,
"10": 12
}

Dictionary/recursive/ counting parts (exercise[LOGIC])

problem: create a recursive function that given an input key, would return the amount of basic components to build the given input key.
EX 1) input = "Engine"
output = Engine ==> metal: 3, rubber: 2
EX 2) input = "metal"
output = metal ==> metal: 1
EX 3) input = "piston"
output = piston ==> metal: 1, rubber: 1
car= {
"Engine" : ["pistons", "timing belt", "metal" ,"metal"],
"Pistons" : ["Metal", "rubber"],
"timing belt" : ["rubber"],
"metal" : [],
"rubber" : []
}
my code has different variable names and key name, but it's the same idea
parts = {
'A': ['B', 'B', 'C'],
'B': [],
'C': ['D','E','F'],
'D': [],
'E': ['B','D'],
'F': []
}
#above here its user input
counter_dictio = {
'A': [],
'B': [],
'C': [],
'D': [],
'E': [],
'F': []
}
def desamble(key, dictionary):
#check if array is empty
#ccounter +=1
if (len(dictionary[key])) == 0:
counter_dictio[key].append(key)
#if array is populated
#enter to this array
#desample(i, dictionary)
else:
for i in dictionary[key]:
desamble(i, dictionary)
key = "A"
desamble(key, parts)
One way to go is:
from collections import Counter
car= {
"engine": ["pistons", "timing belt", "metal", "metal"],
"pistons": ["metal", "rubber"],
"timing belt": ["rubber"],
"metal": [],
"rubber": []
}
def ingredients(key, dct):
if dct[key] == []:
yield key
else:
for sub_part in dct[key]:
yield from ingredients(sub_part, dct)
print(*ingredients('engine', car)) # metal rubber rubber metal metal
print(Counter(ingredients('engine', car))) # Counter({'metal': 3, 'rubber': 2})
ingredients makes a generator of ingredients, so you can use Counter to count them.
Here is code that will group by your components
from collections import defaultdict
parts = {
'A': ['B', 'B', 'C'],
'B': [],
'C': ['D', 'E', 'F'],
'D': [],
'E': ['B', 'D'],
'F': []
}
result = defaultdict(dict)
for k, v in parts.items():
row = result[k] # used to create empty dict on initial empty list
for item in v:
if row.get(item) is None:
row[item] = 1
else:
row[item] += 1
This will result in following dict
{'A': {'B': 2, 'C': 1}, 'B': {}, 'C': {'D': 1, 'E': 1, 'F': 1}, 'D': {}, 'E': {'B': 1, 'D': 1}, 'F': {}}
another solution without using recursively, and for a predetermined list would be:
#==== user input====
key = "E"
parts = {
'A': ['B', 'B', 'C'],
'B': [],
'C': ['D','E','F'],
'D': [],
'E': ['B','D'],
'F': []
}
#====end user input=====
#Function for the predetermined dictionary
def desamble(key, dictionary):
if key == "B" or key == "D" or key == "F":
print(key + "==> " + key + ": 1")
elif key == "E":
print(key + "==> " + "B: 1, D: 1" )
elif key == "C":
print(key + "==> " + "B: 1, D: 2, F: 1" )
elif key == "A":
print(key + "==> " + "B: 3, D: 2, F: 1" )
else:
print("Key " + key + " is not defined in dictionary")
#====end====
desamble(key, parts)
Another recursive way to solve this problem, adding a solution for the problem of circularity, meaning that in case that the parts call to eachother.
EX)
dictionary = {
"A": "B",
"B": "A"
}
from typing iport Counter
def func(key, dictionary, current=None):
if not current:
current = set() # could also be a list
if key in current:
raise ValueError # or whichever
if not dictionary.get(key):
return [key]
ret = []
for subkey in dictionary[key]:
ret.extend(func(subkey, dictionary, current.union({key})))
return ret
Print(Counter(func("A"), parts))
#by officerthegeeks

Moving a single key value pair from one dictionary to another

I'm working on building out a basic store in python, with a dictionary of items and their prices. I'm using a dictionary for the cart, and I want users to be able to add items to the cart. For this, I'm aiming to copy a key and value from the products dictionary to the cart dictionary. How can I do this?
products = {"Pencil": 1, "Notebook": 2, "Backpack": 3, "Pens": 2, "Markers": 5, "Whiteboard": 30}
cart = {}
def addToCart():
productToAdd = input("What would you like to add? ")
for k,v in products.items():
if productToAdd == k:
price = v
cart[productToAdd] = cart[v]
break
products = {"Pencil": 1, "Notebook": 2, "Backpack": 3, "Pens": 2, "Markers": 5, "Whiteboard": 30}
cart = {}
def addToCart():
try:
productToAdd = input("What would you like to add? ")
cart[productToAdd]=products[productToAdd]
except KeyError:
print("No such product")
Note that python is case sensitive 'pencil' and 'Pencil' are not the same.
If you are sure the products are meant to be Capital-letter first you can use
productToAdd = input("What would you like to add? ").title()
Assuming that user will choose items from that list(particularly from keys) then:
products = {"Pencil": 1, "Notebook": 2, "Backpack": 3, "Pens": 2, "Markers": 5,
"Whiteboard": 30}
cart = {}
def addToCart():
productToAdd = input("What would you like to add? ")
if not productToAdd.title() in products: # for removing caps confusion
print('No such item')
else: cart[productToAdd] = products[productToAdd]
>>> addToCart()
What would you like to add? Pencil
>>> cart
{'Pencil': 1}
You can make use of dict.setdefault(key, default=None)
Example:
def addToCart():
productToAdd = input("What would you like to add? ")
cart[productToAdd]=products.setdefault(productToAdd, 'No such product')
I had to use raw_input or it would not take in the string such as 'Pencil'.
This is how you copy key value pairs.
products = {"Pencil": 1, "Notebook": 2, "Backpack": 3, "Pens": 2, "Markers": 5, "Whiteboard": 30}
cart = {}
def addToCart():
productToAdd = raw_input("What would you like to add? ")
for k,v in products.items():
print(k)
if productToAdd == k:
cart[k] = v
break
addToCart()
print(cart)

how to check values of dictionary in Python?

d1 = {'name': 'Sagar','age': 25}
d2 = {'name': 'Sassdr', 'age':122}
d3 = {'name': 'Saga23weer', 'age':123344}
d4 = {'name': '2133Sagar', 'age':14322}
ch = input("Enter your value: ")
How can I search inputted value from these dictionaries?
and if found value then it returns Found else return not found.
Why are a search value in different dictionary rather than in one??
Try this
merge all dictionary in one
d5 = {**d1, **d2, **d3, **d4}
and then check
if ch in d5 .values():
print "Found"
else:
print "Not Found"
Make a list of dictionaries and search in it:
d1 = {'name': 'Sagar','age': 25}
d2 = {'name': 'Sassdr', 'age':122}
d3 = {'name': 'Saga23weer', 'age':123344}
d4 = {'name': '2133Sagar', 'age':14322}
d = [d1,d2,d3,d4]
def check(ch):
for entry in d:
if entry["name"] == ch:
return("found")
return ("Not found")
while True:
ch = input("Enter your value: ")
if ch == "stop":
break
print(check(ch))
Output:
>>>
Enter your value: Sagar
found
Enter your value: Someone
Not found
Enter your value: 2133Sagar
found
Enter your value: stop
The effect you want is called key swap. This snippet is the implementation:
def keyswap(yourdict):
cache = {}
for i in yourdict.keys():
cache[yourdict[i]] = i
for i in cache.keys():
yourdict[i] = cache[i]
del cache
It keyswaps inplace.
You can use following code
Python2
def IsFound():
list_dict = [d1, d2, d3, d4]
values_list = []
for each in list_dict:
values_list += each.values()
ch = input('enter your value')
if ch in values_list:
return 'Found'
else:
return 'Not Found'
Python3
def IsFound():
dict = {**d1, **d2, **d3, **d4}
ch = input('enter your value')
if ch in dict.values():
return 'Found'
else:
return 'Not Found'
you need to do:
get the values of dict;
search all dicts;
mark result as "Found" if matches.
for step 1:
dict.values()
for step 2:
there's many way to combine all dicts, as everybody gives.
you can pick all values first to set a new list, then search if your input matches like this:
# combine all dicts
d = d1.values() + d2.values() +d3.values() + d4.values()
# judge if matches
if ch in d:
# do something
hope this code can release your confuse.

Rewrite the code without using objects in python

When not using objects i am finding it difficult to store and parse through the data. Looking for ways where i can shorten the code using generator comprehension.
for a problem where input to the program code is as below
Courses
TRAN~Transfiguration~1~2011-2012~Minerva McGonagall
CHAR~Charms~1~2011-2012~Filius Flitwick
Students
SLY2301~Hannah Abbott
SLY2302~Euan Abercrombie
SLY2303~Stewart Ackerley
SLY2304~Bertram Aubrey
SLY2305~Avery
SLY2306~Malcolm Baddock
SLY2307~Marcus Belby
SLY2308~Katie Bell
SLY2309~Sirius Orion Black
Grades
TRAN~1~2011-2012~SLY2301~AB
TRAN~1~2011-2012~SLY2302~B
TRAN~1~2011-2012~SLY2303~B
TRAN~1~2011-2012~SLY2305~A
TRAN~1~2011-2012~SLY2306~BC
TRAN~1~2011-2012~SLY2308~A
TRAN~1~2011-2012~SLY2309~AB
CHAR~1~2011-2012~SLY2301~A
CHAR~1~2011-2012~SLY2302~BC
CHAR~1~2011-2012~SLY2303~B
CHAR~1~2011-2012~SLY2305~BC
CHAR~1~2011-2012~SLY2306~C
CHAR~1~2011-2012~SLY2307~B
CHAR~1~2011-2012~SLY2308~AB
EndOfInput
Expected Output
SLY2301~Hannah Abbott~9.5
SLY2302~Euan Abercrombie~7.5
SLY2303~Stewart Ackerley~8.0
SLY2304~Bertram Aubrey~0
SLY2305~Avery~8.5
SLY2306~Malcolm Baddock~6.5
SLY2307~Marcus Belby~8.0
SLY2308~Katie Bell~9.5
SLY2309~Sirius Orion Black~9.0
I managed to solve it using objects but is there any other way to write the code without using objects?
import sys
from Courses.Courses import Course
from Students.Students import Student
from Grades.Grades import Grade
courses = []
students = []
grades = []
gradeDict = {'A':10,'AB':9,'B':8,'BC':7,'C':6,'CD':5,'D':4}
courseCodeDict = {}
def readInput():
isSectionStart=True
while True:
# Reading data from console
input_var = raw_input()
if "EndOfInput" != input_var:
if input_var in "Courses Students Grades":
section=input_var
isSectionStart=True
else:
isSectionStart=False
if not isSectionStart:
extractDataFromRawData(input_var,section)
else:
break;
#printData(courses,students,grades)
calculateGradeAverage(grades,courses)
def calculateGradeAverage(grades,courses):
print("Calculating Average now...")
gradeRollNumberDict={}
courseGradeDict={}
gradesSet = {}
for course in courses:
courseCodeDict.update({course.course_code : 1})
for grade in grades:
if gradeRollNumberDict.get(grade.roll_number) == None:
grade.totalGradePoint = grade.grade
gradeRollNumberDict.update({grade.roll_number : grade.totalGradePoint})
else:
grade.totalGradePoint= grade.grade + gradeRollNumberDict.get(grade.roll_number)
gradeRollNumberDict.update({grade.roll_number : grade.totalGradePoint})
if courseGradeDict.get(grade.roll_number) == None:
grade.totalCourseTaken = courseCodeDict.get(grade.course_code)
courseGradeDict.update({grade.roll_number : courseCodeDict.get(grade.course_code)})
else:
grade.totalCourseTaken= courseCodeDict.get(grade.course_code) + courseGradeDict.get(grade.roll_number)
courseGradeDict.update({grade.roll_number : grade.totalCourseTaken})
for grade in grades:
grade.avgGrade = grade.totalGradePoint/grade.totalCourseTaken
grade.avgGrade = round(grade.avgGrade)
seenGrades = set()
uniqueGrades = []
grades.reverse()
for grade in grades:
if grade.roll_number not in seenGrades:
uniqueGrades.append(grade)
seenGrades.add(grade.roll_number)
#uniqueGrades.reverse()
for a in uniqueGrades:
print(a.roll_number)
#print(uniqueGrades)
grades=uniqueGrades
grades.sort(key=lambda grade:grade.roll_number)
for grade in grades:
print("RollNumber: {0} \t Total CourseTaken: {1} \t Total Grade Point: {2} \t Avg Grade: {3}".format(grade.roll_number,grade.totalCourseTaken,grade.totalGradePoint,grade.avgGrade))
def extractDataFromRawData(input_data,section):
if "Courses" == section:
courses.append(createCourseObject(input_data))
elif "Students" == section:
students.append(createStudentObject(input_data))
elif "Grades" == section:
grades.append(createGradeObject(input_data))
else:
print("Invalid input!!! Exiting the system...")
sys.exit()
def createCourseObject(input_data):
courseInputData = input_data.split("~")
course = Course(courseInputData[0],courseInputData[1],courseInputData[2],courseInputData[3],courseInputData[4])
return course
def createStudentObject(input_data):
studentInputData = input_data.split("~")
student = Student(studentInputData[0],studentInputData[1])
return student
def createGradeObject(input_data):
gradeInputData = input_data.split("~")
grade = Grade(gradeInputData[0],gradeInputData[1],gradeInputData[2],gradeInputData[3],gradeDict[gradeInputData[4]])
return grade
def printData(courses,students,grades):
printObject(courses,"Courses")
printObject(students,"Students")
printObject(grades,"Grades")
def printObject(list,object):
print("Printing %s"%object)
for data in list:
print(data)
if __name__ == '__main__':
readInput()
Code:
from collections import OrderedDict
from pprint import pprint as pp
SEPARATOR = "~"
GRADE_DICT = {
"A": 10,
"AB": 9,
"B": 8,
"BC": 7,
"C": 6,
"CD": 5,
"D": 4
}
def read_input_from_file(file_name="input.txt"):
course_list= list()
student_list = list()
grade_list = list()
section_map = {
"Courses": course_list,
"Students": student_list,
"Grades": grade_list,
}
with open(file_name) as f:
current_item = None
for line in f:
line = line.strip()
if line in section_map:
current_item = section_map[line]
elif line == "EndOfInput":
break
elif current_item is not None:
current_item.append(line)
else:
print("Ignoring line: {}".format(line))
return course_list, student_list, grade_list
def convert_names(name_list):
ret = OrderedDict()
for element in name_list:
id, name = element.split(SEPARATOR)
ret[id] = name
return ret
def convert_grades(grade_list):
ret = dict()
for element in grade_list:
course_id, student_id, grade_id = element.rsplit(SEPARATOR, 2)
ret.setdefault(student_id, dict())[course_id] = grade_id
return ret
def main():
course_list, student_list, grade_list = read_input_from_file()
student_dict = convert_names(student_list)
print("\n[SECTION 0]: Student IDs and names:\n")
pp(student_dict)
exam_stat_dict = convert_grades(grade_list)
print("\n[SECTION 1]: Grades organized by students and courses:\n")
pp(exam_stat_dict)
print("\n[SECTION 2]: Final Grades:\n")
for student_id in student_dict:
if student_id in exam_stat_dict:
grade_dict = exam_stat_dict[student_id]
grades_sum = sum([GRADE_DICT.get(item, 0) for item in grade_dict.values()])
print(SEPARATOR.join([student_id, student_dict[student_id], str(grades_sum/len(grade_dict))]))
else:
print(SEPARATOR.join([student_id, student_dict.get(student_id), "0.0"]))
if __name__ == "__main__":
main()
Output (I'm placing it before the Notes, since I'm going to refer to it from there):
(py35x64_test) c:\Work\Dev\StackOverflow\q45987148>python a.py
[SECTION 0]: Student IDs and names:
OrderedDict([('SLY2301', 'Hannah Abbott'),
('SLY2302', 'Euan Abercrombie'),
('SLY2303', 'Stewart Ackerley'),
('SLY2304', 'Bertram Aubrey'),
('SLY2305', 'Avery'),
('SLY2306', 'Malcolm Baddock'),
('SLY2307', 'Marcus Belby'),
('SLY2308', 'Katie Bell'),
('SLY2309', 'Sirius Orion Black')])
[SECTION 1]: Grades organized by students and courses:
{'SLY2301': {'CHAR~1~2011-2012': 'A', 'TRAN~1~2011-2012': 'AB'},
'SLY2302': {'CHAR~1~2011-2012': 'BC', 'TRAN~1~2011-2012': 'B'},
'SLY2303': {'CHAR~1~2011-2012': 'B', 'TRAN~1~2011-2012': 'B'},
'SLY2305': {'CHAR~1~2011-2012': 'BC', 'TRAN~1~2011-2012': 'A'},
'SLY2306': {'CHAR~1~2011-2012': 'C', 'TRAN~1~2011-2012': 'BC'},
'SLY2307': {'CHAR~1~2011-2012': 'B'},
'SLY2308': {'CHAR~1~2011-2012': 'AB', 'TRAN~1~2011-2012': 'A'},
'SLY2309': {'TRAN~1~2011-2012': 'AB'}}
[SECTION 2]: Final Grades:
SLY2301~Hannah Abbott~9.5
SLY2302~Euan Abercrombie~7.5
SLY2303~Stewart Ackerley~8.0
SLY2304~Bertram Aubrey~0.0
SLY2305~Avery~8.5
SLY2306~Malcolm Baddock~6.5
SLY2307~Marcus Belby~8.0
SLY2308~Katie Bell~9.5
SLY2309~Sirius Orion Black~9.0
Notes:
This is a "slightly" modified version of your code, that only uses stuff from Python standard library
Code explanation:
read_input_from_file (since it's only a helper function, I'm not going to insist much on it):
I saved the input (copy/paste) in a file (called it input.txt), and every time the program runs, it loads the data from there (the reason is obvious)
It (populates and) returns 3 lists (curses, students and grades from your code)
convert_names:
Converts every student name entry (as given in input) into a dictionary*: {id: name} (e.g. "SLY2301~Hannah Abbott" -> {"SLY2301": "Hannah Abbott"}) - the key will be id
*Since in a regular Python dictionary ([Python]: Mapping Types — dict) the keys are ordered by their hash (the hash function can change between Python versions), there's almost 100% chance that the dictionary elements won't be stored in the order they were inserted (as an example you could type in the Python console {1:2, 0:1} and you'll see that it will output {0: 1, 1: 2}), I'm using [Python]: class collections.OrderedDict([items]) which ensures the key order
The return value can be seen in program output (SECTION 0)
convert_grades:
This is where (most of) the magic takes place
Converts every grade entry (as given in input) in a dictionary: {student_id : {course_id: grade_id}} (the last 2 values are aggregated in an inner dictionary; e.g. "TRAN~1~2011-2012~SLY2301~AB" -> {"SLY2301": {"TRAN~1~2011-2012": "AB"}}). For that, I'm using [Python]: str.rsplit(sep=None, maxsplit=-1) with a maxsplit value of 2, as I don't care about the ~s in TRAN~1~2011-2012
If a student_id is present more than once (was to more than 1 course exam), I am just adding the course_id and grade_id in the inner dictionary (this is where [Python]: setdefault(key[, default]) comes into play)
The return value can be seen in program output (SECTION 1)
main:
The program main function. Here, I'm making use of the other functions and display the final data in a proper manner to the user (SECTION 2)
If there was a student that wasn't at any exam, like Bertram Aubrey (the id is not present in the exam statistics dictionary), I just print the id, name and 0.0
Otherwise, I calculate the arithmetic average from the grades in the inner dictionary (I am using [Python]: list Comprehensions to convert the grades into actual numbers, [Python]: sum(iterable[, start]) to sum the grades, then I divide the total by the number of inner dictionary keys) and display it, together with the id and name
The code runs with Python3 and Python2
#EDIT0:
Adding read_input function (read_input_from_file with minimum and trivial modifications) to read input from keyboard:
def read_input():
course_list= list()
student_list = list()
grade_list = list()
section_map = {
"Courses": course_list,
"Students": student_list,
"Grades": grade_list,
}
current_item = None
while(1):
line = input()
if line in section_map:
current_item = section_map[line]
elif line == "EndOfInput":
break
elif current_item is not None:
current_item.append(line)
else:
print("Ignoring line: {}".format(line))
return course_list, student_list, grade_list
Notes:
In order for this function to work with Python2, this code should be added at the beginning of the file:
import sys
if sys.version_info.major < 3:
input = raw_input
You can also use the input.txt file to test the code with large datasets (like provided in the question, without having to manually type all the data) like this:
python a.py < input.txt
#CristiFati using your code i managed to tweak to solve my problem as below.
from collections import OrderedDict
import sys
SEPARATOR = "~"
GRADE_DICT = {
"A": 10,
"AB": 9,
"B": 8,
"BC": 7,
"C": 6,
"CD": 5,
"D": 4
}
def read_input_from_file():
course_list= list()
student_list = list()
grade_list = list()
section_map = {
"Courses": course_list,
"Students": student_list,
"Grades": grade_list,
}
current_item = None
while True:
line = input()
#line = line.strip()
if line != "EndOfInput":
if line in section_map:
current_item = section_map[line]
elif current_item is not None:
current_item.append(line)
else:
print("Ignoring line: {}".format(line))
else:
break
return course_list, student_list, grade_list
def convert_names(name_list):
ret = OrderedDict()
for element in name_list:
id, name = element.split(SEPARATOR)
ret[id] = name
return ret
def convert_grades(grade_list):
ret = dict()
for element in grade_list:
course_id, student_id, grade_id = element.rsplit(SEPARATOR, 2)
ret.setdefault(student_id, dict())[course_id] = grade_id
return ret
def main():
course_list, student_list, grade_list = read_input_from_file()
student_list.sort()
student_dict = convert_names(student_list)
exam_stat_dict = convert_grades(grade_list)
for student_id in student_dict:
if student_id in exam_stat_dict:
grade_dict = exam_stat_dict[student_id]
grades_sum = sum([GRADE_DICT.get(item, 0) for item in grade_dict.values()])
print(SEPARATOR.join([student_id, student_dict[student_id], str(round(float(grades_sum/len(grade_dict)),2))]))
else:
print(SEPARATOR.join([student_id, student_dict.get(student_id), "0"]))
if __name__ == "__main__":
main()

Categories

Resources