0

Is there any way to take 2 user input with a space between them and convert the first input to key and the second input to the corresponding value to that key? I know this can be done with lists like this.

ls = list(map(int, input("").split(" ")))

Is there anyway to take inputs from the user and instead of converting them to a list, convert them to a dictionary?

2 Answers2

0

If at all you wish to have more than 2 values and would like to split your data in dictionary in the manner in which you want, you can use this generalized code. (It will work for your two input also)

ls = list(map(int, input("Input: ").split(" ")))
iterator = iter(ls)
my_dict = {}
for val in iterator:
    my_dict[val] = next(iterator)
print(my_dict)

Output:

Input: 34 56 78 89
{34: 56, 78: 89}

But ensure that the odd position entry in your input doesn't repeat, otherwise your key will be overwritten with a new value.

Prasad
  • 5,946
  • 3
  • 30
  • 36
0

using itertools

If you want to do it in a single line.

import itertools
dict_value = dict(itertools.zip_longest(*[iter(list(map(int, input("").split(" "))))] * 2, fillvalue=""))

and in simplified way is

import itertools
ls = list(map(int, input("").split(" ")))
dict_value = dict(itertools.zip_longest(*[iter(ls)] * 2, fillvalue=""))

if you curious to know list to dict conversation have a look here

R.A.Munna
  • 1,699
  • 1
  • 15
  • 29