am new to python, please share logic for below concept - python

Eg:
ECE_student_list = [['section-1', [["sai",'science'], ["rama",'maths']]],
['section-2', [["seetha",'science'], ["ravana",'maths']]]]
I have to print student name and subject by passing key as section name.
for Eg : if the key is 'section-1' first student then it should print "sai",'science'
second student ,then it should print "rama",'maths'
please share the logic in python.

Won't share the code directly. That you have to learn and experiment on your own. Although I can tell you what you can expect as your output.
You can create a dictionary in python and add section-1, section-2 as the keys and the list of students as value for each key.
Your dictionary structure will be something like this:
{
'section-1' : [
{'sai':'science'},
{'rama':'math'}
],
'section-2':[
{'sai':'science'},
{'rama':'math'}
]
}

Related

search through a nested dictionary and record the steps

say I have a dictionary like this:
profile = {'Person':{'name':['John'], 'Description':['smart']}}
I am looking for a piece of code that searches for 'John', and 'Description', but doesn't know where they are in the nested dictionary. I also want to the code to print something like this:
John is located in the value of profile['Person']
Description is located in the key of profile['Person']
How can I do that? Any help will be appreciated. Thank you
Learn how to iterate through a nested dictionary. In Python Dictionary, items() method is used to return the list with all dictionary keys with values. Indexing [ ] is used to access an element of a nested dictionary
profile = {'Person':{'name':['John'], 'Description':['smart']},'Person1':{'name':['John1'], 'Description':['smart1']}}
for p_id, p_info in profile.items():
for key in p_info:
if p_info[key][0] == "John":
print(p_info[key][0],"is located in the value of profile['",p_id,"']")
if p_info[key][0] == "smart":
print(p_info[key][0],"is located in the value of profile['",p_id,"']")

Create nested python dictionary

I am using the python code below to extract some values from an excel spreadsheet and then push them to an html page for further processing. I would like to modify the code below so that I can add additional values against each task, any help
the code below does spit out the following:
{'line items': {'AMS Upgrade': '30667', 'BMS works':
'35722'}}
How can I revise the code below so that I can add 2 more values against each task i.e. AMS Upgrade and BMS works
and get the likes of (note the structure below could be wrong)
{'line items': {'AMS Upgrade': {'30667','100%', '25799'}},{'BMS works':
{'10667','10%', '3572'}} }
Code:
book = xlrd.open_workbook("Example - supporting doc.xls")
first_sheet = book.sheet_by_index(-1)
nested_dict = {}
nested_dict["line items"] = {}
for i in range(21,175):
Line_items = first_sheet.row_slice(rowx=i, start_colx=2, end_colx=8)
if str(Line_items[0].value) and str(Line_items[1].value):
if not Line_items[5].value ==0 :
nested_dict["line items"].update({str(Line_items[0].value) : str(Line_items[1].value)})
print nested_dict
print json.dumps(nested_dict)
*** as requested see excel extract below
In Python, each key of a dict can only be associated with a single value. However that single value can be a dict, list, set, etc that holds many values.
You will need to decide the type to use for the value associated with the 'AMS Upgrade' key, if you want it to hold multiple values like '30667','10%', '222'.
Note: what you have written:
{'30667','100%', '25799'}
Is a set literal in Python.

Modifying a python dictionary from user inputted dot notation

I'm trying to provide an API like interface in my Django python application that allows someone to input an id and then also include key/values with the request as form data.
For example the following field name and values for ticket 111:
ticket.subject = Hello World
ticket.group_id = 12345678
ticket.collaborators = [123, 4567, 890]
ticket.custom_fields: [{id: 32656147,value: "something"}]
On the backend, I have a corresponding Dict that should match this structure (and i'd do validation). Something like this:
ticket: {
subject: "some subject I want to change",
group_id: 99999,
collaborator_ids: [ ],
custom_fields: [
{
id: 32656147,
value: null
}
]
}
1) I'm not sure exactly the best way to parse the dot notation there, and
2) Assuming I am able to parse it, how would I be able to change the values of the Dict to match what was passed in. I'd imagine maybe something like a class with these inputs?
class SetDictValueFromUserInput(userDotNotation, userNewValue, originalDict)
...
SetDictValueFromUserInput("ticket.subject", "hello world", myDict)
Fastest way is probably splitting the string and indexing based on seperation. For example:
obj = "ticket.subject".split(".")
actual_obj = eval(obj[0]) # this is risky, they is a way around this if you just use if statements and predifined variables.
actual_obj[obj[1]] = value
To have further indexing where an object like ticket.subject.name might work try using a for loop as so.
for key in obj[1:-2]: # basically for all the values in between the object name and the defining key
actual_obj = actual_obj[key] # make the new object based on the value in-between.
actual_obj[obj[-1]] = value

How to get the desired value of the dictionary?

First off, i'm new to python and trying to create a dynamic dictionary :
editdistances = { r.name : editdistance.eval(baseline.result, r.result)}
note that i'm running a for r in values: above r having 2 instances name and value.Now the thing is i want to append the value part(editdistance.eval(baseline.result, r.result) in a table
table.append(editdistances[x])
this is what i tried but pretty sure it's wrong because it's not referencing the value. How can i fix it and still know what's the name (r.name) of each value in the table.
Edit: Just noticed another issue in editdistances = { r.name : editdistance.eval(baseline.result, r.result)} basically let's say i have 3 students, student1,student 2 and student 3. And i want to input 3 grades for each one at a time using a loop, basically first iteration student1 :16..second iteration student1:16 student2 :12..third iteration student1:16 student2 :12 student3:9..4th iteration student1:16,7 student2 :12 student3:9 ...and so on, how can i do that and still be able to refer to each grade indivudually assuming each refers to a different course.
editdistances = { 'r.name' : "editdistance.eval(baseline.result, r.result)"}
table=[]
for r in editdistances:
table.append(editdistances[r])
print (table)
Output
['editdistance.eval(baseline.result, r.result)']
You can access the value for a given key in a dictionary this way (assuming r has a property values:
for value in r.values:
table.append(editdistances[value])
If values is a method of r then you also need to add brackets:
for value in r.values():
table.append(editdistances[value])
This seems more like you're asking how to use a dictionary.
"how can i do that and still be able to refer to each grade indivudually assuming each refers to a different course"
Create a dictionary with each student as a key in the first level.
Then each student is a dictionary, with a course-name for keys, and the grades attached as values:
students = {
'student1' : {'class1' : 'grade1', 'class2' : 'grade2', 'class3' : grade3'},
'student2' : {'class1' : 'grade1', 'class2' : 'grade2', 'class3' : grade3'},
'student3' : {'class1' : 'grade1', 'class2' : 'grade2', 'class3' : grade3'}
}
for student in students:
for class_name in student:
# print the student's name, class name, and their grade for that class.
print (student, class_name, students[student][class_name])
Given your current question, the question itself isn't written that clearly
And you have dependency code/data-structuring that you mention briefly but don't allow to be fully described.
Please provide that dependency code so we can see what you're talking about. For example, the sentence "I am doing this in a for loop" is way more characters than
just pasting the exact and original code.

Getting and adding specific values to dictionary

Nice to meet you all.
I'm new to Python and I've a "Maze solving" project. The project itself is a bit confusing and Professor wants users to use List for such tasks. The problem is I'm using dictionary to store input values instead of lists because I find dictionaries easier to work with in C#.
This is how I'm storing data:
ArcsDict.update({'Arc' + str(InputNum) : {'StartPoint': StartPoint, 'EndPoint': EndPoint, 'Price': Price}} )
This is how the dictionary looks:
{"Arc1": { "StartPoint" : 1, "EndPoint" : 2, "Price" : 10 }, "Arc2":{"StartPoint" : 3, "EndPoint" : 5, "Price" : 15 }}
Now I want to get only StartPoints and EndPoints from the dictionary and add them to another dictionary called NodesDict
for val in ArcsDict.keys():
for value in ArcsDict[val].keys():
print ArcsDict[val][value]
NodesDict.update({'Nodes' + str(InputNum) : {'XPoint': ArcsDict[val][value], 'YPoint': ArcsDict[val][value] }})
The above code "for loop" stuff sometimes makes sense to me and sometimes it doesn't but is there any way I can ONLY get the StartPoints and EndPoints from each Arc and add them to NodesDict then print the points as:
(0, 0)
(1, 3)
We are ONLY allowed to use default Python modules. Any help will be appreciated!
Edit: If anyone could explain how dictionary works in Python in a bit detail that would be appreciated as well! I would like to convince my professor to use dictionary instead of lists while making it sound easier and understandable at the same time.

Categories