How to print defaultdict variable without its type

2020-08-14 07:28发布

问题:

In the following code:

from collections import defaultdict

confusion_proba_dict = defaultdict(float)

for i in xrange(10):
    confusion_proba_dict[i] = i + 10

print confusion_proba_dict

Output is:

defaultdict(<type 'float'>, {0: 10, 1: 11, 2: 12, 3: 13, 4: 14, 5: 15, 6: 16, 7: 17, 8: 18, 9: 19})

But, I need output to be:

{0: 10, 1: 11, 2: 12, 3: 13, 4: 14, 5: 15, 6: 16, 7: 17, 8: 18, 9: 19}

How can I do it?

回答1:

just transform it to a regular dict

print( dict(confusion_proba_dict) )

but if you are going to use like that, just use a regular dict as you don't use any of the advantages of defaultdict



回答2:

Python 2:

print dict(confusion_proba_dict)

Python 3:

print(dict(confusion_proba_dict))


回答3:

Funny solution ! ( works also if you have defaultdict of defaultdict ! )

import json
import pprint
pprint.pprint(json.loads(json.dumps(confusion_proba_dict)))