Reputation: 405
I have a dictionary (named dict1
) that has the following structure:
dict1 = {
'Classroom': [{
'Subject': "Calculus",
'Students': [
{'Name': "Joe", 'Age': 12, 'Weight': 126, 'Gender': "Male"},
{'Name': "Doug", 'Age': 13, 'Weight': 95, 'Gender': "Male"},
{'Name': ..., 'Age': ..., 'Weight': ..., 'Gender': ...}
]
}]
}
The list (which contains name, age, weight, and gender) within this dictionary is very long, and I wanted to parse the Name, Age, and Gender out, and append them onto another list like this:
mylist = [("Joe", 12, "Male"), ("Doug", 13, "Male"), ... ]
I tried seraching online and tinkered around with code such as this:
mylist = []
dict2 = dict1['Classroom'][0]['Students'][0]['Name']
mylist.append(dict2)
But what happens is that it only appends the first name (Joe). Furthermore, I'm not sure how to parse three items (name, age, and gender) at the same time. Does anyone have a way to do this without having to use libraries?
Upvotes: 1
Views: 1968
Reputation: 449
student_list = []
classroom_list = dict1['Classroom']
# this is the first iteration list
for classroom in classroom_list:
student_list = classroom['Students']
# this is the second iteration list
for student in student_list:
student_list.append(student['Name'], student['Age'], student['Gender'])
#student_list = [("Joe", 12, "Male"), ("Doug", 13, "Male"), ... ]
Upvotes: 1
Reputation: 2603
Your dict1
contains one key, 'Classroom'
whose value is a list
with one entry.
That entry, is also a dict
which contains two keys. You want the 'Students'
key as that contains the list of all the students. It is a list. Iterate through that list and group the fields into a tuple.
It is technically a list ['Students']
nested within a dictionary ['Classroom'][0]
within a list ['Classroom']
within a dictionary dict
.
The code will be
mylist = []
studentlist = dict1['Classroom'][0]['Students']
for s in studentlist:
m = (s['Name'], s['Age'], s['Gender'])
mylist.append(m)
For the test case
classroom = {'Classroom':
[{'Subject': "Calculus", 'Students':
[
{'Name': "Joe", 'Age': 12, 'Weight': 126, 'Gender': "Male"},
{'Name': "Doug", 'Age': 13, 'Weight': 95, 'Gender': "Male"},
{'Name': "Omg", 'Age': 50, 'Weight': 99, 'Gender': "Female"}
]
}]
}
you will end up with
[('Joe', 12, 'Male'), ('Doug', 13, 'Male'), ('Omg', 50, 'Female')]
Upvotes: 2