Search code examples
pythonlistgroup

How to access subgroup in list with Python


I have a list with subgroups within. I made subgrouping based on similarity of fund name. How do I select/identify a group within a list?

mylist = [
    {'American Funds Cnsrv Gr & Inc A', 'American Funds Cnsrv Gr & Inc R-5E', 'American Funds Cnsrv Gr & Inc F-1', 'American Funds Cnsrv Gr & Inc R-6', 'American Funds Cnsrv Gr & Inc R-5', 'American Funds Cnsrv Gr & Inc F-3', 'American Funds Cnsrv Gr & Inc R-4', 'American Funds Cnsrv Gr & Inc F-2'}
    {'MFS Conservative Allocation R3', 'MFS Conservative Allocation R2', 'MFS Conservative Allocation R6', 'MFS Conservative Allocation I', 'MFS Conservative Allocation A', 'MFS Conservative Allocation R4'}, 
    {'American Funds Cnsrv Gr & Inc 529-A', 'American Funds Cnsrv Gr & Inc 529-F-3', 'American Funds Cnsrv Gr & Inc 529-F-2', 'American Funds Cnsrv Gr & Inc 529-F-1'}]

For example how to I call/select 2nd group: {'MFS Conservative Allocation R3', 'MFS Conservative Allocation R2', 'MFS Conservative Allocation R6', 'MFS Conservative Allocation I', 'MFS Conservative Allocation A', 'MFS Conservative Allocation R4'}

My eventual goal is to keep only one fund from each group that is the best share class, but first I need a way to identify each subgroup.

Thanks


Solution

  • You can slice or indice the list index:

    mylist = [{'American Funds Cnsrv Gr & Inc A', 'American Funds Cnsrv Gr & Inc R-5E', 'American Funds Cnsrv Gr & Inc F-1', 'American Funds Cnsrv Gr & Inc R-6', 'American Funds Cnsrv Gr & Inc R-5', 'American Funds Cnsrv Gr & Inc F-3', 'American Funds Cnsrv Gr & Inc R-4', 'American Funds Cnsrv Gr & Inc F-2'}, {'MFS Conservative Allocation R3', 'MFS Conservative Allocation R2', 'MFS Conservative Allocation R6', 'MFS Conservative Allocation I', 'MFS Conservative Allocation A', 'MFS Conservative Allocation R4'}, {'American Funds Cnsrv Gr & Inc 529-A', 'American Funds Cnsrv Gr & Inc 529-F-3', 'American Funds Cnsrv Gr & Inc 529-F-2', 'American Funds Cnsrv Gr & Inc 529-F-1'}]
    
    MFSC = mylist[1]
    print(MFSC)
    

    Output:

    {'MFS Conservative Allocation R2', 'MFS Conservative Allocation I', 'MFS Conservative Allocation A', 'MFS Conservative Allocation R3', 'MFS Conservative Allocation R4', 'MFS Conservative Allocation R6'}
    

    But the element of list is a set so set element can appear in a different order every time you use them, and cannot be referred to by index or key.

    MFSC = list(mylist[1])
    print(MFSC)
    

    Output:

    ['MFS Conservative Allocation R4', 'MFS Conservative Allocation R6', 'MFS Conservative Allocation I', 'MFS Conservative Allocation A', 'MFS Conservative Allocation R3', 'MFS Conservative Allocation R2']