-2

i have the following code:

#!/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) )

i am getting the following output:

    {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})

i dont want to see the type ,i just want to see the date:

    {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})}

i looked at other thrieds ,and they recomended to convert it to dic:

print( dict(d) )

or

print( dict.__repr__(d) )

i am still getting the type

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
askpython
  • 75
  • 2
  • 8
  • You can just use `print(d)`, there is no need to call the `__repr__` unbound method. Even if `dict` had a `__str__` method, should use `repr(d)`, or `d.__repr__()`, before reaching for `dict.__repr__(d)`. – Martijn Pieters Feb 16 '18 at 09:49

2 Answers2

2

You have a nested structure, a defaultdict containing defaultdict instances. You only converted the outermost object; you need to create a deep copy instead.

You could generate a new dictionary with a dict comprehension to create a copy 2 levels deep:

{k: dict(v) for k, v in d.items()}

Alteratively, build your data structure without using defaultdict objects:

d = {}
for (a, b), c in farm_sub_count:
    inner = d.setdefault(a, {})
    inner[b] = inner.get(b, 0) + c
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

With two "for" loops:

 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)

The output is

{'Farm': [{'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Premium': 3}, {'Red Hat Enterprise Linux for Virtual Datacenterswith Smart Management, Standard': 2}]}