Beta Projects Beta Projects - 1 year ago 80
Python Question

Make a dictionary in Python from input values

Seems simple, yet elusive, want to build a dict from input of [key,value] pairs separated by a space using just one Python statement. This is what I have so far:

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


A1023 CRT
A1029 Regulator
A1030 Therm

Desired Output:

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

Answer Source

using str.splitines() and str.split():

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'}

str.splitlines([keepends]) -> list of strings

Return a list of the lines in S, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

str.split([sep [,maxsplit]]) -> list of strings

Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download