python - 合并字典列表的常见元素并将不常见元素存储在新键中
问题描述
我有一个非常大的字典,其中的键包含项目列表,这些是无序的。我想将某些元素分组到一个新键中。例如
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 等包中可用,可以使用现有方法。
解决方案
尝试
result = (
df.groupby(['name', 'state'])
.apply(lambda x: x[['areacode', 'mobile']].to_dict(orient='records'))
.reset_index(name='contactoptions')
).to_dict(orient='records')
推荐阅读
- javascript - 第一个模块和“意外的令牌 {”
- angular6 - 导航到其他页面时,继续显示导航选项卡
- c# - 是否可以索引和切片 ReadOnlySpan
使用 Unicode 文本元素? - python - 当一切都合法接受 csv 文件时,为什么我会收到语法错误?
- python - matplotlib 中的直方图未正确分箱
- c++ - C++ 类成员是空指针
- maven - 是否可以在 Maven 中使用不同的存储库进行解析和部署?
- apache-spark - 结构化流式提取每个 id 的最新值
- momentjs - 使用 Moment js 生成具有动态 VTIMEZONE 的 ics
- kubernetes - kubernetes 如何决定为 IPAM 调用哪个网络插件?