0

I want to have a 2D array, the first Parametre is the name of student and the second one is his result.

i try this :

listStudentResult = [] 
listStudentResult.append([])
listStudentResult[0].append("Alex")
listOfasinEan[0].append(20)

lisStudentResult.append([])
listStudentResult[1].append(Paul)
listStudentResult[1].append(15)

How can i have the result of Alex? i don't want listStudentResult[0][1] i need something like

listStudentResult[0]["Alex"]
1
  • 1
    You need a list of dicts. Commented Jun 3, 2016 at 10:05

3 Answers 3

2

By looking at your requirement, I would suggest you to use dictionary in python.

To explain dictionary, I will take your example

listStudentResult = dict()
listStudentResult['Alex'] = 20
listStudentResult['Paul'] = 15

You can access the elements using listStudentResult['Alex'].

Sign up to request clarification or add additional context in comments.

Comments

2

Use dictionaries:

listStudentResult = [] 
listStudentResult.append({"Alex": 20})
listStudentResult.append({"Paul": 15})

Comments

1

Complex class:

class AutoVivification(dict):
    """Implementation of perl's autovivification feature. Has features from both dicts and lists,
    dynamically generates new subitems as needed, and allows for working (somewhat) as a basic type.
    """
    def __getitem__(self, item):
        if isinstance(item, slice):
            d = AutoVivification()
            items = sorted(self.iteritems(), reverse=True)
            k,v = items.pop(0)
            while 1:
                if (item.start < k < item.stop):
                    d[k] = v
                elif k > item.stop:
                    break
                if item.step:
                    for x in range(item.step):
                        k,v = items.pop(0)
                else:
                    k,v = items.pop(0)
            return d
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

    def __add__(self, other):
        """If attempting addition, use our length as the 'value'."""
        return len(self) + other

    def __radd__(self, other):
        """If the other type does not support addition with us, this addition method will be tried."""
        return len(self) + other

    def append(self, item):
        """Add the item to the dict, giving it a higher integer key than any currently in use."""
        largestKey = sorted(self.keys())[-1]
        if isinstance(largestKey, str):
            self.__setitem__(0, item)
        elif isinstance(largestKey, int):
            self.__setitem__(largestKey+1, item)

    def count(self, item):
        """Count the number of keys with the specified item."""
        return sum([1 for x in self.items() if x == item])

    def __eq__(self, other):
        """od.__eq__(y) <==> od==y. Comparison to another AV is order-sensitive
        while comparison to a regular mapping is order-insensitive. """
        if isinstance(other, AutoVivification):
            return len(self)==len(other) and self.items() == other.items()
        return dict.__eq__(self, other)

    def __ne__(self, other):
        """od.__ne__(y) <==> od!=y"""
        return not self == other

Simple class:

class vividict(dict):  
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

examples:

d = vividict()
print d

d['John']['results'] = [90]

print d

d['John']['results'].append(10) 

print d     

d = AutoVivification()

print d

d['John']['results'][0]=20
print d
d['John']['results'].append(20)

for result in [30,25,60,100,99]:
    d['John']['results'].append(result)

onlyNumbers=True

lastKey=max(d['John']['results'].keys())
for n,result in enumerate('5 15 25 33.1 40'.split()):
    n+=lastKey
    d['John']['results'][n]=result if not onlyNumbers else float(result)

print d

from pprint import pprint as ppr

ppr(d)

'''
output:
{}
{'John': {'results': [90]}}
{'John': {'results': [90, 10]}}
{}
{'John': {'results': {0: 20}}}
{'John': {'results': {0: 20, 1: 20, 2: 30, 3: 25, 4: 60, 5: 100, 6: 5.0, 7: 15.0, 8: 25.0, 9: 33.1, 10: 40.0}}}
{'John': {'results': {0: 20,
                      1: 20,
                      2: 30,
                      3: 25,
                      4: 60,
                      5: 100,
                      6: 5.0,
                      7: 15.0,
                      8: 25.0,
                      9: 33.1,
                      10: 40.0}}}   


'''

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.