Make a dictionary in Python from input values

前端 未结 10 1372
情深已故
情深已故 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:46

    I have taken an empty dictionary as f and updated the values in f as name,password or balance are keys.

    f=dict()
    f.update(name=input(),password=input(),balance=input())
    print(f)
    
    0 讨论(0)
  • 2021-02-03 12:49
    n=int(input())
    pair = dict()
    
    for i in range(0,n):
            word = input().split()
            key = word[0]
            value = word[1]
            pair[key]=value
    
    print(pair)
    
    0 讨论(0)
  • 2021-02-03 12:49

    Take input from user:

    input = int(input("enter a n value:"))
    
    dict = {}
    
    for i in range(input):
    
        name = input() 
    
        values = int(input()) 
    
        dict[name] = values
    print(dict)
    
    0 讨论(0)
  • 2021-02-03 12:57
    n = int(input("enter a n value:"))
    d = {}
    
    for i in range(n):
        keys = input() # here i have taken keys as strings
        values = int(input()) # here i have taken values as integers
        d[keys] = values
    print(d)
    
    0 讨论(0)
  • 2021-02-03 12:57
    record = int(input("Enter the student record need to add :"))
    
    stud_data={}
    
    for i in range(0,record):
        Name = input("Enter the student name :").split()
        Age = input("Enter the {} age :".format(Name))
        Grade = input("Enter the {} grade :".format(Name)).split()
        Nam_key =  Name[0]
        Age_value = Age[0]
        Grade_value = Grade[0]
        stud_data[Nam_key] = {Age_value,Grade_value}
    
    print(stud_data)
    
    0 讨论(0)
  • 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'}
    
    0 讨论(0)
提交回复
热议问题