Kashif
Kashif

Reputation: 35

How to create a Python dictionary from the user inputted data in a specific format?

What I want to do is first insert the key into the dictionary then after hitting Enter insert the value. This is to be done for n number of key, value pairs.

n = 3
d = dict(input().split() for _ in range(n))
print (d)

Using this method I have to insert key and value at the same time, which I don't want.

Upvotes: 1

Views: 51

Answers (2)

DevLounge
DevLounge

Reputation: 8437

You could do that:

n = 3
d = {input('Key:'): input('Value:') for _ in range(n)}
print (d)

You were not that far!

Upvotes: 2

Cameron McFee
Cameron McFee

Reputation: 396

output = {}
for _ in range(n):
   key = input("Enter Key:")
   value = input("Enter Value:")
   output[key] = value
return output

your pseudocode had it right. You could try to code golf it to one line with multiple inputs but that will make it less readable.

Upvotes: 2

Related Questions