How to take input for dictionary in Python | Example code

  • by

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 (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

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.