我有以下代码:
#!/usr/bin/python
farm_sub_count = [[['Farm', u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Premium'], 2], [['Farm', u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Standard'], 2], [['Farm', u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Premium'], 1]]
from collections import defaultdict
d = defaultdict(lambda: defaultdict(int))
for (a, b), c in farm_sub_count:
d[a][b] += c
print( dict(d) )
print( dict.__repr__(d) )
我得到以下输出:
{Farm - defaultdict(<type 'int'>, {u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Standard': 2, u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Premium': 3})
我不想看到类型,我只是想看日期:
{Farm: {u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Standard': 2, u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Premium': 3})}
我看着其他人,他们建议把它转换为dic:
print( dict(d) )
或
print( dict.__repr__(d) )
我仍然得到类型
答案 0 :(得分:2)
您有嵌套结构,defaultdict
包含defaultdict
个实例。你只转换了最外面的对象;你需要创建一个深层副本。
您可以使用字典理解生成一个新字典,以创建2级深度的副本:
{k: dict(v) for k, v in d.items()}
另外,使用defaultdict
对象构建数据结构:
d = {}
for (a, b), c in farm_sub_count:
inner = d.setdefault(a, {})
inner[b] = inner.get(b, 0) + c
答案 1 :(得分:0)
有两个“for”循环:
from collections import defaultdict
d = defaultdict(lambda: defaultdict(int))
for (a, b), c in farm_sub_count:
d[a][b] += c
objArray = []
printobj = {}
finalobj = {}
for i in d:
for k in d[i]:
printobj = {k : d[i][k]}
objArray.append(printobj)
finalobj= {i: objArray}
print(finalobj)
输出
{'Farm': [{'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Premium': 3}, {'Red Hat Enterprise Linux for Virtual Datacenterswith Smart Management, Standard': 2}]}