Make a dictionary in Python from input values

前端 未结 10 1371
情深已故
情深已故 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 12:58

    n = int(input())          #n is the number of items you want to enter
    d ={}                     
    for i in range(n):        
        text = input().split()     #split the input text based on space & store in the list 'text'
        d[text[0]] = text[1]       #assign the 1st item to key and 2nd item to value of the dictionary
    print(d)
    

    INPUT:

    3
    
    A1023 CRT
    
    A1029 Regulator
    
    A1030 Therm
    

    NOTE: I have added an extra line for each input for getting each input on individual lines on this site. As placing without an extra line creates a single line.

    OUTPUT:

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

提交回复
热议问题