Make a dictionary in Python from input values

前端 未结 10 1375
情深已故
情深已故 2021-02-03 12:06

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:



        
10条回答
  •  醉话见心
    2021-02-03 13:02

    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.

提交回复
热议问题