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”

  1. thank you but won’t work becuase my dict format access key is 3digit such code requires single digit number format to access

Leave a Reply

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