Reputation: 746
My SQL Structure is like below:
CourseId StudentId CourseName
6001 101 Password
6002 102 Awareness
6003 101 Security
I'm pulling data into tuples
using pyodbc cursor
and creating list of ordered dicts for processing.
for tup in tuples:
doc = collections.OrderedDict()
doc['studentid'] = tup.StudentId
doc['courses'] = [{courseid: tup.CourseId, 'coursename': tup.CourseName}]
insArray.append(doc)
Now, if the student Id already exists in any of the ordered array in the insArray
list I need to append the course details in the courses array.
For the above given records the expected insArray
result would be:
[OrderedDict([('studentid', 101), ('courses', [{'courseid': 6001, 'coursename':'Password'},{'courseid': 6003, 'coursename':'security'}])]), OrderedDict([('studentid', 102), ('courses', [{'courseid': 6002, 'coursename':'Awareness'}])])]
Upvotes: 0
Views: 5146
Reputation: 7058
Instead of a list insArray
as recordset you could use and OrderedDict, and then through the magic of dict.get(key, default)
append to a previous list of courses
insArray = collections.OrderedDict()
for tup in tuples:
student_id = tup.StudentId
courses = insArray.get(student_id, collections.OrderedDict()).get('courses', list())
courses.append({'courseid': tup.CourseId, 'coursename': tup.CourseName})
# list.append alters the original list and returns None
doc = collections.OrderedDict()
doc['studentid'] = student_id
doc['courses'] = courses
insArray[student_id] = doc
OrderedDict([(101,
OrderedDict([('studentid', 101),
('courses',
[{'courseid': 6001, 'coursename': 'Password'},
{'courseid': 6003, 'coursename': 'Security'}])])),
(102,
OrderedDict([('studentid', 102),
('courses',
[{'courseid': 6002,
'coursename': 'Awareness'}])]))])
If you want a list as insArray, you can retrieve that with list(insArray.values())
Upvotes: 1