python – 将字典列表转换为唯一的字典列表
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 将字典列表转换为唯一的字典列表,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2628字,纯文字阅读大概需要4分钟。
内容图文
![python – 将字典列表转换为唯一的字典列表](/upload/InfoBanner/zyjiaocheng/800/ce6e7efda34540b98a881aee490ffdfc.jpg)
我一直在努力解决以下问题而没有成功.
我有一个如下所示的数据结构:
[ { 'ROOT': [
{ 'firstElem': 'gc-3/1/0'},
{ 'SecondElem': '5.0.0.1'},
{ 'ThirdElem': '127.3.15.1'},
{ 'index': 16},
{ 'function': 'session'},
{ 'hw': '0.0.0.0'},
{ 'sw': '1.50.1.3'},
{ 'resources': [ { 'cpu-info': [ { 'cpu-peak-load': 1},
{ 'cpu-avg-load': 1}]},
{ 'memory-total': 1},
{ 'memory-used': 2}]},
]},
{ 'ROOT': [
{ 'firstElem': 'gc-4/1/0'},
{ 'SecondElem': '5.0.0.2'},
{ 'ThirdElem': '127.3.4.1'},
{ 'index': 5},
{ 'function': 'stand'},
{ 'hw': '0.0.0.0'},
{ 'sw': '1.50.1.3'},
{ 'resources': [ { 'cpu-info': [ { 'cpu-peak-load': 1},
{ 'cpu-avg-load': 1}]},
{ 'memory-total': 1},
{ 'memory-used': 2}]},
]}
]
我想遍历这个数据结构并将所有dict-element与相同名称组合在一起,然后创建一个列表.
这很难解释,我创建了一个我正在寻找的示例结构:
{
"ROOT": [
{
"firstElem": "gc-3/1/0",
"SecondElem": "5.0.0.1",
"ThirdElem": "128.0.2.19",
"index": "13",
"function": "session",
"hw": "1.11.0.0 ",
"sw": "1.50.0.228 ",
"resources": {
"cpu-info": {
"cpu-peak-load": "1",
"cpu-avg-load": "1",
},
"memory-total": "1",
"memory-used": "2",
},
},
{
"firstElem": "gc-4/1/0",
"SecondElem": "5.0.0.1",
"ThirdElem": "128.0.2.19",
"index": "13",
"function": "session",
"hw": "1.11.0.0 ",
"sw": "1.50.0.228 ",
"resources": {
"cpu-info": {
"cpu-peak-load": "8",
"cpu-avg-load": "1",
},
"memory-total": "1",
"memory-used": "2",
},
}
],
}
我坚持使用原始数据结构,无法更改它.任何帮助表示赞赏.
上面提供的结构只是一个例子,因为数据是动态接收的,我不知道标签名称.因此,请不要提供使用特定标记名称的解决方案.
解决方法:
这是一种方式:
>>> from collections import defaultdict
>>> def combine(item):
# Easy return if not a list: element itself
if type(item) != type([]):
return item
# else call recursion
first_ret = [(i.items()[0][0], combine(i.items()[0][1])) for i in item]
# Here we group by same keys if any ('ROOT', for instance)
count_keys = defaultdict(list)
for couple in first_ret:
count_keys[couple[0]].append(couple[1])
return dict((k, v if len(v) > 1 else v[0]) for k, v in count_keys.iteritems())
我不得不对ROOT节点进行分组,但它似乎正在工作:
>>> pprint(combine(l))
{'ROOT': [{'SecondElem': '5.0.0.1',
'ThirdElem': '127.3.15.1',
'firstElem': 'gc-3/1/0',
'function': 'session',
'hw': '0.0.0.0',
'index': 16,
'resources': {'cpu-info': {'cpu-avg-load': 1,
'cpu-peak-load': 1},
'memory-total': 1,
'memory-used': 2},
'sw': '1.50.1.3'},
{'SecondElem': '5.0.0.2',
'ThirdElem': '127.3.4.1',
'firstElem': 'gc-4/1/0',
'function': 'stand',
'hw': '0.0.0.0',
'index': 5,
'resources': {'cpu-info': {'cpu-avg-load': 1,
'cpu-peak-load': 1},
'memory-total': 1,
'memory-used': 2},
'sw': '1.50.1.3'}]}
>>>
内容总结
以上是互联网集市为您收集整理的python – 将字典列表转换为唯一的字典列表全部内容,希望文章能够帮你解决python – 将字典列表转换为唯一的字典列表所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。