Skip to content

How to take input for dictionary in Python | Example code

Using str.splitlines() and str.split() function will take input for dictionary in Python. Or you can use a split function with for loop for it.

Example take input for dictionary in Python

Simple example code.

Using str.splitlines() and str.split():

This way only one key-value pair can take.

strs = input("Enter key values pairs: ")

d = dict(x.split() for x in strs.splitlines())

print(d)

Output:

How to take input for dictionary in Python

Taking n number of input for dictionary

n = 3

d = dict(input("Enter key and value: ").split() for _ in range(n))

print(d)

Output:

Enter key and value: a 1
Enter key and value: b 2
Enter key and value: c 3
{‘a’: ‘1’, ‘b’: ‘2’, ‘c’: ‘3’}

Do comment if you have any doubts or suggestions on this Python input code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

1 thought on “How to take input for dictionary in Python | Example code”

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading