Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Pretty printing A Dictionary

The default way of printing a dictionary is as follows,


employee={'name','john','age',36,'salary',50000}
print(employee)
{36, 'salary', 'name', 50000, 'john', 'age'}

If the dictionary is large , and in order to make it presentable and readable, there is a way.
import json module (JavaScript Object Notation) and use dumps() function
syntax:
json.dumps(<dictionary name>,indent=2)

eg:
import json
employee={'name':'john','age':36,'salary':50000}
print(json.dumps(employee,indent=2))

{
"name": "john",
"age": 36,
"salary": 50000
}

Counting frequency of elements in a list using Dictionary


import json
list = ['a','b','a','c','d','c','c']
frequency = {}
for item in list:
frequency[item] = list.count(item)
print(json.dumps(frequency,indent=2))

{
"a": 2,
"b": 1,
"c": 3,
"d": 1
}

#A program to count the frequency of a list of elements using a dictionary


import json
text=” Welcome to python programming”
words=text.split()
d={}
for i in words:
key=i
if key not in d:
count=word.count(key)
d[key]=count
print(“counting frequencies:”)
print(json.dumps(d,indent=2))

counting frequencies:
{
"Welcome": 1,
"to": 1,
"python": 1,
"programming": 1
}

You might also like