associative array

Chris Rebert clp2 at rebertia.com
Thu Apr 1 07:10:42 EDT 2010


On Thu, Apr 1, 2010 at 3:58 AM, Javier Montoya <jmontoyaz at gmail.com> wrote:
> On Mar 31, 7:36 pm, Gary Herron <gher... at digipen.edu> wrote:
>> JavierMontoyawrote:
>> > Dear all,
>>
>> > I'm a newbie in python and would be acknowledge if somebody could shed
>> > some light on associative arrays.
>> > More precisely, I would like to create a multi-dimensional associative
>> > array. I have for example a list of students which are identified
>> > uniquely by their student IDs. Additionally, for each student I have
>> > some information: FirstName, LastName, etc.
>>
>> > The array would have then the following form:
>> > [StudentID] => [FirstName][LastName][Telephone]...[ ... ]
>>
>> > I would like to be able to access a field directly by using a
>> > StudentID
>> > [StudentID][FirstName]
>> > [StudentID][LastName]
>>
>> > How could I manipulate such an array (create the array, add elements,
>> > access data)?
>>
>> > Best wishes
>>
>> Create a class for student with attributes for ID, FirstName, LastName, etc.
>>
>>   class Student:
>>       def __init__(self, id, FirstName, ...):
>>           self.id = id
>>           self.FirstName = FirstName
>>           ...
>>
>> then whenever you create a student object, use a dictionary to associate
>> the object with its is
>>   AA = {} # An empty dictionary
>>   s = Student(...)
>>   AA[s.id] = s
>>   ... and repeat for many students...
>>
>> Then to access a student's object given an id:
>>   s = AA[id]
>>   print s.id, s.FirstName, s.LastName, ...
>>
>> I'd *not* call this a multi-dimension association, but rather just an
>> association between student objects and their ids.
>>
>> Hope that helps,
>>
>> Gary Herron
>>
>> --
>> Gary Herron, PhD.
>> Department of Computer Science
>> DigiPen Institute of Technology
>> (425) 895-4418
>
> Dear all,
>
> Thanks for your suggestions, it worked! As Gary suggested, I created a
> 'student' class and mapped its objects to a dictionary.
> Is it possible to sort the dictionary by the student's grades in
> descending order?

Dictionaries are not ordered collections, so they themselves cannot be sorted.

However, if you want a list of students sorted in the manner you stated:
class_rank = list(garys_dictionary.values())
class_rank.sort(key=lambda student: student.grade, reverse=True)

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list