简体   繁体   中英

Save loop output with list into dictionary in Python

I have some point codes in two column and I'm looking for a path between them. For example:

COL_A         COL_B
B1011         B1012
B1012         B1014
B1013         B2017
B1014         B1018
...
B1018         B2022

For each of them I need a path from the first untill the last (without broke). For example, for B1011 it will B1012,B1014, B1018, ...B2022. I have write a code which goes through all values and put it in the list, but in that version I need to input string of the point code. Now I need to automated it and return dictionary as an output. For example {'B1011' : ['B1012', 'B1014', 'B1018', ...'B2022'], ... }

Code I have:

list_for_output = []
def func_top(x,num):
    for i in range(len(x[x.COL_A==num])):
        list_for_output.append(x[x.COL_A==num]['COL_B'].iloc[i])
    for i in range(len(x[x.COL_A==num])):
        if x[x.COL_A==list_for_output[-(i+1)]].empty == True:
            return
        else:
            func_top(x,list_for_output[-(i+1)])
            return

How to add output to dictionary in form : {COL_A:list_for_output} for each row in dataframe? Thanks. Desired output:

    {'B1011' : ['B1012', 'B1014', 'B1018', ...'B2022'], 
     'B1012': ['B1014', 'B1018', ...'B2022'], 
     'B1014':['B1018', ...'B2022'],
     'B1013':['B2017'],... }

Try to modify this code

import pandas as pd
from collections import defaultdict

df = pd.DataFrame({'COL_A': ['B1011','B1012','B1013','B1014','B1015','B1018'],
                  'COL_B': ['B1012','B1014','B2017','B1018','B2021','B2022']})

a= df.groupby(['COL_A']).apply(lambda grp: grp.COL_B.to_dict()).to_dict()
print (a)

Result

{'B1011': {0: 'B1012'}, 'B1012': {1: 'B1014'}, 'B1013': {2: 'B2017'}, 'B1014': {3: 'B1018'}, 'B1015': {4: 'B2021'}, 'B1018': {5: 'B2022'}}

This is not exact solution , But its just a example to give you direction.

Using recursive approach:

import pandas as pd
from collections import defaultdict

df = pd.DataFrame({'COL_A': ['B1011','B1012','B1013','B1014','B1015','B1018'],
                  'COL_B': ['B1012','B1014','B2017','B1018','B2021','B2022']})

a=[i for i in df['COL_A']]
b=[i for i in df['COL_B']]

final_result=[]
def main_function(bn):
    dict_1={}


    path = []

    if not bn:
        return 0
    else:
        value_2 = []
        def hello(a_, b_, c):



            if not c:
                return 0
            else:

                aa = a_[c[0]]


                bb = b_[c[0]]

                if bb in a_:
                    value = []
                    value.append(aa)
                    if bb not in path:
                        path.append(bb)
                    bn = a_.index(bb)

                    cn = b_[bn]

                    if cn not in path:
                        path.append(cn)

                    value_2.extend(value)





                    return hello(a_, b_, c[1:])


                else:

                    if "{}".format({aa:bb}) not in final_result:
                        final_result.append("{}".format({aa:bb}))


                    return hello(a_, b_, c[1:])

        hello(a, b, bn)
        if path:
            dict_1[value_2[0]]=path
            if dict_1 not in final_result:
                final_result.append(dict_1)

        main_function(bn[1:])

main_function(list(range(0,len(a))))

print(final_result)

Format the result as you want.

output:

["{'B1013': 'B2017'}", "{'B1015': 'B2021'}", "{'B1018': 'B2022'}", {'B1011': ['B1012', 'B1014', 'B1018', 'B2022']}, {'B1012': ['B1014', 'B1018', 'B2022']}, {'B1014': ['B1018', 'B2022']}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM