RookiePythonTMZ
RookiePythonTMZ

Reputation: 1

Get or delete value from a nested list in Python

I get 112 values from excel file. I transfer them to a dict, and then a list. They are grades from three exams based on student name.

Form like this :

    grade = ["Mike", {"First": 0.9134344089913918, "Second": 0.9342180467620398, "Third": 0.8703466591191937}]
["Lisa", {"First": 0.8940552022848847, "Second": 0.9342180467620398, "Third": 0.881441786523737}]
["James", {"First": 0.8324328746220233, "Second": 0.9342180467620398, "Third": 0.683570699129642}]

Above are the first three set of value. My goal is just obtain the first exam value from the list. The result should be like this:

["Mike", {"First": 0.9134344089913918}]
["Lisa", {"First": 0.8940552022848847}]
["James", {"First": 0.8324328746220233}]

Two ways. a) delete the second and third exam value. b) just get the first exam value.

Is there anyone can help me. Since it is not a typical list...but it is not a dict. I use print type(grade)....It shows its a list.

Thank you.

Upvotes: 0

Views: 102

Answers (3)

shx2
shx2

Reputation: 64318

It is more natural to represent your initial structure as a dict (as well as the resulting structure).

all_grades = dict(grade)

Now, use a dict-comprehension, creating a new one-item-dict for each student:

first_grades = {
    name: { 'First': grades_dict['First'] }
    for name, grades_dict in all_grades.items()
}

Here's a generalisation of this concept:

first_grades = {
    name: {
        grade_key: grades_dict[grade_key]
        for grade_key in ( 'First', )
    }
    for name, grades_dict in all_grades.items()
}

You end up with:

{'James': {'First': 0.8324328746220233},
 'Lisa': {'First': 0.8940552022848847},
 'Mike': {'First': 0.9134344089913918}}

Upvotes: 1

Kuishi
Kuishi

Reputation: 157

I'm not sure if I understand your data structure. You said you have a dict before you made a list. Maybe you could use this:

Data structure

>>> grade
{'Lisa': {'Third': 0.881441786523737, 'First': 0.8940552022848847, 'Second': 0.9
342180467620398}, 'Mike': {'Third': 0.8703466591191937, 'First': 0.9134344089913
918, 'Second': 0.9342180467620398}}

The result

>>> [{key:{'First':value['First']}} for key,value in grade.items()]
[{'Lisa': {'First': 0.8940552022848847}}, {'Mike': {'First': 0.9134344089913918}
}]

Upvotes: 0

sundar nataraj
sundar nataraj

Reputation: 8692

grade = [["Mike", {"First": 0.9134344089913918, "Second": 0.9342180467620398, "Third": 0.8703466591191937}],["James", {"First": 0.8324328746220233, "Second": 0.9342180467620398, "Third": 0.683570699129642}]]

newdict=[]

for person,marks in grade:
    print marks
    newdict.append([person,{'First':marks['First']}])

#output [['Mike', {'First': 0.9134344089913918}], ['James', {'First': 0.8324328746220233}]]

please make sure your grades should be a list of list containing the person and marks as mine.then we can easily retrieve value

Upvotes: 0

Related Questions