3

I want to know how to output the name, not the values, of each index (and sub-index) in a list and in sub-lists.

For example, let's say I have a main list, which has 3 other lists each containing 5 sub-lists. Here is a small example to clarify:

List1 = [SubList1, SubList2, SubList3, SubList4, SubList5]
List2 = [Apple, Banana, Orange, Pear, Grape]
List3 = [Red, Yellow, Orange, Green, Purple]


Lists = [List1, List2, List3]

MainList = [Lists]

How can I print out 'List1'?

When I type in

MainList[0][0]

it outputs

[SubList1, SubList2, ..., Sublist5]

I want the actual name of the index, not its values.

I thought about using dictionary keys, but the report generator that I am using for the XML conversion outputs all the data into lists. Does this mean I have no choice but to modify my report generator script to output the data into dictionaries?

3
  • 2
    try to use dict() since it is key: value based collection Commented Oct 9, 2015 at 14:36
  • 3
    You can't, the name doesn't work like that. It's a label, not an attribute. Recommended reading: nedbatchelder.com/text/names.html Commented Oct 9, 2015 at 14:36
  • 1
    list index doesn't have name, but key of the dictionaries does have name, use it. Commented Oct 9, 2015 at 14:37

5 Answers 5

2

Try to use dict() for that purpose:

List1 = ['SubList1', 'SubList2', 'SubList3', 'SubList4', 'SubList5']
List2 = ['Apple', 'Banana', 'Orange', 'Pear', 'Grape']
List3 = ['Red', 'Yellow', 'Orange', 'Green', 'Purple']


xd = {'List1': List1, 'List2': List2, 'List3': List3}

print xd['List1']

for k, v in xd.iteritems():
    if v == List1:
        print k

>>> ['SubList1', 'SubList2', 'SubList3', 'SubList4', 'SubList5']
>>> List1
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, I tried your suggestion and I am receiving the following error: AttributeError: 'dict' object has no attribute 'iteritems' I am using Python 3.4 by the way
Found the answer to my problem: stackoverflow.com/questions/30418481/…
@MikeIssa yep. You didn't need iteritems() in Python 3. It is generator by default. Just use items().
Sadly, that's O(n) solution.
2

You seem to misunderstand. List1 in your example is a variable name. It is not stored in the Lists array, only its value is stored. So you are not going to get List1 out of Lists. Array indexes are integers and the index of List1 in Lists is 0. As the other commenter suggested you might want to convert your Lists structure into a dict.

Lists = {}
Lists['List1'] = [SubList1, SubList2, SubList3, SubList4, SubList5]
Lists['List2'] = [Apple, Banana, Orange, Pear, Grape]
Lists['List3'] = [Red, Yellow, Orange, Green, Purple]

print(Lists.keys())

Comments

1

Quick solution:

class NamedList(list):
    __slots__ = ['__name__'] # optimisation, can be ommited
    def __init__(self, name, *args):
        super().__init__(*args)
        self.__name__ = name
    def __repr__(self):
        return "%s(%r, %s)" % (type(self).__name__, self.__name__, super().__repr__())

test = NamedList('test', [1, 2, 3])
print(test)
print(test.__name__)

Output:

NamedList('test', [1, 2, 3])
test

Comments

1

list object has no name attributes, you should use pandas.Series as follow:

import pandas as pds
List1 = pds.Series([SubList1, SubList2, SubList3, SubList4, SubList5],name='List1')
List2 = pds.Series([Apple, Banana, Orange, Pear, Grape],name='List2')

you find the name like this:

print List1.name,List2.name

A list of list become a pandas.DataFrame:

Lists = pds.DataFrame([List1, List2, List3])

To answer your question, you should proceed as follow:

-each sublist become a series

Sublist = pds.Series([...],name='Sublist')

-each list become a dataframe:

List = pds.DataFrame([Sublist1,Sublist2,..])

-"the" Lists become a dict:

Lists = {'List1' : List1,
         'List2' : List2,
         ...
         }

-you get the name:

for name_list,list in Lists.items(): 
     name_list,list.columns

1 Comment

Please add some example code to show how it solves the problem.
1

If your lists always are stored as variables, you can retrieve their names by using some sort of identity dict (sadly there is none in standard library):

names = IdentityWeakKeyDict((obj, name for name, obj in locals().items()))

names should now map objects to their names.

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.