首页 > 解决方案 > 合并字典列表的常见元素并将不常见元素存储在新键中

问题描述

我有一个非常大的字典,其中的键包含项目列表,这些是无序的。我想将某些元素分组到一个新键中。例如

input= [{'name':'emp1','state':'TX','areacode':'001','mobile':123},{'name':'emp1','state':'TX','areacode':'002','mobile':234},{'name':'emp1','state':'TX','areacode':'003','mobile':345},{'name':'emp2','state':'TX','areacode':None,'mobile':None},]

对于上述输入,我想将区号和移动设备组合在一个新键中contactoptions

opdata = [{'name':'emp1','state':'TX','contactoptions':[{'areacode':'001','mobile':123},{'areacode':'002','mobile':234},{'areacode':'003','mobile':345}]},{'name':'emp2','state':'TX','contactoptions':[{'areacode':None,'mobile':None}]}]

我现在正在进行两次长时间的迭代。我想更有效地实现相同的记录数量很大。如果在 pandas 等包中可用,可以使用现有方法。

标签: pythonpandas

解决方案


尝试

result = (
    df.groupby(['name', 'state'])
      .apply(lambda x: x[['areacode', 'mobile']].to_dict(orient='records'))
      .reset_index(name='contactoptions')
    ).to_dict(orient='records')

推荐阅读