Python 快速迭代三个字典的方法?
我正在处理三本非常大的字典,它们看起来像这样:Python 快速迭代三个字典的方法?,python,python-3.x,pandas,loops,dictionary,Python,Python 3.x,Pandas,Loops,Dictionary,我正在处理三本非常大的字典,它们看起来像这样: 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] } 我正在寻找这样的输出
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] }
我正在寻找这样的输出:
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]
我试过的是:
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)
这真的是没有效率和优化的方式来完成这项任务。我想用熊猫
如何以最小的时间复杂度完成此任务
谢谢大家! 试试这个方法:-
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)
输出:-
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)
那么:
pd.DataFrame({i:d for i,d in enumerate([dict_a,dict_b,dict_c])} )
输出:
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]
这里有一条路
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]
因为这些是字典,所以您只需要迭代一个。您可以使用该键从其他键获取相应的值 例如:
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])
为了可读性,我可能只对dict\u a中的键使用
。然后final_dict
赋值(除第一个外)可以统一编写为final_dict[''.''.]..append(…[key])
(也可以很好地确认,所有三个字典都有相同的键集。)我在考虑键的集合并集,然后迭代键来构建输出——以防某个dict恰好缺少某个条目。这将获得所有dict中的所有键,因此您只需要一个循环。O(n)+O(n)=O(n)