本文介绍了合并Python字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  dict1 = {'paul':100,'john ':80,'ted':34,'herve':10} 
dict2 = {'paul':'a','john':'b','ted':'c' :'d'}

output = {'paul':[100,'a'],'john':[80,'b'],'ted':[34,'c' ],彼得:[无,'d'],'herve':[10,无]}



解决方案
  output = dict (k,[dict1 [k],dict2.get(k)])for dict1)
output.update((k,[无,dict2 [k]])for dict2中的k如果k不在dict1)


I am trying to merge the following python dictionaries as follow:

dict1= {'paul':100, 'john':80, 'ted':34, 'herve':10}
dict2 = {'paul':'a', 'john':'b', 'ted':'c', 'peter':'d'}

output = {'paul':[100,'a'], 'john':[80, 'b'], 'ted':[34,'c'], 'peter':[None, 'd'], 'herve':[10, None]}

Is there an efficient way to do this?

解决方案
output = dict((k, [dict1[k], dict2.get(k)]) for k in dict1)
output.update((k, [None, dict2[k]]) for k in dict2 if k not in dict1)

这篇关于合并Python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 05:54