Skip to content

How to take multiple inputs in the dictionary in Python | Example code

  • by

Using input() function with split() function and for in range can use to take multiple inputs in the dictionary in Python.

Example take multiple inputs in the dictionary in Python

Simple example code builds a dict from the input of [key, value] pairs separated by a space using just one Python statement.

n = 3

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

print(d)

Output:

How to take multiple inputs in the dictionary in Python

OR

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

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

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

print(d)

Output:

Enter key values pairs: X 1
{‘X’: ‘1’}

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

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.

Leave a Reply

Discover more from Tutorial

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

Continue reading