Aaditya Ura
Aaditya Ura

Reputation: 12679

Fast way to iterate over three dictionaries?

I am dealing with very large three dictionaries which looks like this:

dict_a = { ( 't','e' ) : [0.5,0.1,0.6],  ( 'a','b' ) : [0.2,0.3,0.9] }

dict_b = { ( 'a','b' ) : [0.1,0.5,0.3] , ( 't','e' ) : [0.6,0.1,0.6] }

dict_c = { ( 'a','b' ) : [0.1,0.5,0.3] , ( 't','e' ) : [0.6,0.5,0.6] }

I am looking for the output like this :

    name    first_value       second_value  third_value

0   (t, e)  [0.5, 0.1, 0.6] [0.6, 0.1, 0.6] [0.6, 0.5, 0.6]
1   (a, b)  [0.2, 0.3, 0.9] [0.1, 0.5, 0.3] [0.1, 0.5, 0.3]

What I've tried is :

final_dict = {'name': [] , 'first_value' : [] ,'second_value': [] , 'third_value': [] }

for a,b in dict_a.items():
    for c,d in dict_b.items():
        for e,f in dict_c.items():
            if a==c==e:
                final_dict['name'].append(a)
                final_dict['first_value'].append(b)
                final_dict['second_value'].append(d)
                final_dict['third_value'].append(f)

Which is really not efficient and optimize way to do this task. I was thinking to use pandas.

How can I do this task in minimal time complexity?

Thank you !

Upvotes: 0

Views: 132

Answers (4)

Kendas
Kendas

Reputation: 2243

Because these are dictionaries, you only need to iterate over one. You can use the key to get the corresponding value from the others.

Example:

for key, value in dict_a.items():
        final_dict['name'].append(key)
        final_dict['first_value'].append(value)
        final_dict['second_value'].append(dict_b[key])
        final_dict['third_value'].append(dict_c[key])

Upvotes: 4

BENY
BENY

Reputation: 323316

Here is one way

pd.concat([pd.Series(x) for x in [dict_a,dict_b,dict_c]],axis=1)
Out[332]: 
                   0                1                2
a b  [0.2, 0.3, 0.9]  [0.1, 0.5, 0.3]  [0.1, 0.5, 0.3]
t e  [0.5, 0.1, 0.6]  [0.6, 0.1, 0.6]  [0.6, 0.5, 0.6]

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150785

How about:

pd.DataFrame({i:d for i,d in enumerate([dict_a,dict_b,dict_c])} )

Output:

                   0                1                2
a b  [0.2, 0.3, 0.9]  [0.1, 0.5, 0.3]  [0.1, 0.5, 0.3]
t e  [0.5, 0.1, 0.6]  [0.6, 0.1, 0.6]  [0.6, 0.5, 0.6]

Upvotes: 1

Vicrobot
Vicrobot

Reputation: 3988

Try this way:-

df = pd.DataFrame([dict_a, dict_b, dict_c], index = ['first_value', 
'second_value', 'third_value']).T
df['names'] = df.index
df.index = [0, 1]
print(df)

Output:-

       first_value     second_value      third_value   names
0  [0.2, 0.3, 0.9]  [0.1, 0.5, 0.3]  [0.1, 0.5, 0.3]  (a, b)
1  [0.5, 0.1, 0.6]  [0.6, 0.1, 0.6]  [0.6, 0.5, 0.6]  (t, e)

Upvotes: 1

Related Questions