Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to create a dictionary from the input of [key, value] pairs separated by a space using just one Python statement. I have executed the below code:

d={}

n = 3

d = [ map(str,raw_input().split()) for x in range(n)]

print d

The output that I am getting: 

A1023 CRT

A1029 Regulator

A1030 Therm

My desired Output:

{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}

1 Answer

0 votes
by (108k points)

In your case, it is better to use str.splitines() and str.split(), kindly refer to the below code:

In [126]: strs="""A1023 CRT

   .....: A1029 Regulator

   .....: A1030 Therm"""

In [127]: dict(x.split() for x in strs.splitlines())

Out[127]: {'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}

If you are beginner and want to know more about Python, then do refer to the below python tutorial:

 

Browse Categories

...