Show each key-value of a dictionary print on a new line in Python
In this tutorial, we’ll look at a few alternative techniques to print the contents of a dictionary in Python line by line.
In Python, output each key-value pair from a dictionary on a new line.
There are various ways to print the content of a dictionary in a new line.
We will use six different ways to implement it.
Items in a dictionary are key-value pairs. So, initially, let’s make a dictionary with the names of students and their grades, i.e.
d = {'CodeSpeedy': 97, 'Yash:': 93, 'xyz:': 94}
Now, let’s print it.
print(d)
it will give output like below,
{'CodeSpeedy': 97, 'Yash:': 93, 'xyz:': 94}
Now, let’s learn ways to print in a new line
1) Input:
import pprint pretty = pprint.PrettyPrinter(width=10) pretty.pprint({'CodeSpeedy': 97, 'Yash:': 93, 'xyz:': 94})
Here, we have imported pprint library. which helps us to print key-value in a new line. you can learn more about it here, pprint
- Output:
{'CodeSpeedy': 97, 'Yash:': 93, 'xyz:': 94}
2) Input:
d = {'CodeSpeedy': 97, 'Yash:': 93, 'xyz:': 94} for k, v in d.items(): print (k, v)
Here, we have used d.items() returns a list of (key, value) and also returns an iterator.
- Output:
CodeSpeedy : 97 Yash : 93 xyz : 94
3) Input:
d = {'CodeSpeedy': 97, 'Yash:': 93, 'xyz:': 94 } [print(key,':',value) for key, value in d.items()]
Here, I have used the same method as above but there is a slight change in way of writing as for loop is mention along with a print statement which is basically for code optimization
- Output:
CodeSpeedy : 97 Yash: : 93 xyz: : 94
4) Input:
d = {'CodeSpeedy': 97, 'Yash:': 93, 'xyz:': 94} print(str(d).replace(', ',',\n '))
Here, I have used str and replace the functionality of python which is the simplest way to print key-value in new line.
- Output:
{'CodeSpeedy': 97, 'Yash:': 93, 'xyz:': 94}
5) Input:
d = {'CodeSpeedy': 97, 'Yash:': 93, 'xyz:': 94} for key in d: print(key, ' : ', d[key])
Above, We can iterate through a dictionary’s keys one by one, then read each key’s value and output it on a single line.
- Output:
CodeSpeedy : 97 Yash: : 93 xyz: : 94
6) Input:
import json d = {'CodeSpeedy': 97, 'Yash:': 93, 'xyz:': 94} print(json.dumps(d, indent=4))
Here, The dumps() method returns a JSON string from a Python object and the indent is to define how many spaces are required.
This gives output in JSON formate
- Output:
{ "CodeSpeedy": 97, "Yash:": 93, "xyz:": 94 }
Leave a Reply