Make complex dictionary from two arrays of keys

sara jones Source

I have df1 and df2. for each element in df1 I want to check if it exist in df2 and print df3

df1=['c_1', 'd_1', 'f_1', 'h_1', 'i_1', 'n_1', 'v_1', 'm_1']

df2=[['lia', 'f_1', 'n_1', 'v_1'], ['eli', 'f_1', 'n_1', 'v_1', 'm_1']]

I want an output like this:

df3=[('f_1', {'lia': 1}), ('n_1', {'lia': 1}), ('v_1', {'lia': 1}),
     ('c_1', {'lia': 0}), ('d_1', {'lia': 0}), ('h_1', {'lia': 0}), 
     ('i_1', {'lia': 0}), ('m_1', {'lia': 0}), ('f_1', {'eli': 1}),
    ...]

I tried some iterations but it didn't work. here is my code.

def st_pl(line, df1):    
 ln=line    
 st=df1    
 l = ln[0]    
 if l:    
  dict_l = {l: 1}    
 if not l:    
  dict_l = {l: 0}    
  li_st = []    
 size = len(ln)    
 for i in range(1, size):    
  tup = (ln[i], dict_l)    
  li_st.append(tup)    
  return li_st
pythondictionary

Answers

answered 3 months ago Ayodhyankit Paul #1

You can try this approach and take help from it:

df1=['c_1', 'd_1', 'f_1', 'h_1', 'i_1', 'n_1', 'v_1', 'm_1']

df2=[['lia', 'f_1', 'n_1', 'v_1'], ['eli', 'f_1', 'n_1', 'v_1', 'm_1']]


final_ist=[]

for i in df1:
    for j in df2:
        if i in j:
            final_ist.append((i,{j[0]:1}))
        else:
            final_ist.append((i,{j[0]:0}))

print(final_ist)

output:

    [('c_1', {'lia': 0}), ('c_1', {'eli': 0}), ('d_1', {'lia': 0}), 
    ('d_1', {'eli': 0}),('f_1', {'lia': 1}), ('f_1', {'eli': 1}), 
    ('h_1', {'lia': 0}), ('h_1', {'eli': 0}),('i_1', {'lia': 0}), 
    ('i_1', {'eli': 0}),('n_1', {'lia': 1}), ('n_1', {'eli': 1}), 
    ('v_1', {'lia': 1}), ('v_1', {'eli': 1}), 
    ('m_1', {'lia': 0}), ('m_1', {'eli': 1})]

comments powered by Disqus