Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print index name in python

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?

like image 739
Mike Issa Avatar asked May 06 '26 00:05

Mike Issa


2 Answers

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
like image 58
xiº Avatar answered May 07 '26 13:05

xiº


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())
like image 25
Mad Wombat Avatar answered May 07 '26 14:05

Mad Wombat