Taking input for dictionary in python

Question:

Can anyone please tell me if it is possible to take the key and value for a dictionary as input in python?
Suppose I have made an empty dictionary. I want to include the key name by taking input from user as well as its corresponding value as well.

Asked By: Sudhanshu Ojha

||

Answers:

This is pretty simple, for each key there is a list of values, note all values will be in string form. You enter the information like this.

Key;

Number of values for that key;

Enter each value seperately

Repeat for each key

Code:

def inputDict(numKeys=10):
    #if you want you could make numKeys an input too(numKeys = int(input("Numkeys?")))
    desiredDict = {}
    #ask key and value for the numKeys
    for nameValuePair in range(numKeys):
        key = input("NextKey:n")
        numVals = int(input("How many values for that key?n"))
        valList = []
        for value in range(numVals):
            valList.append(input("Next valuen"))
        desiredDict[key] = valList
    return desiredDict
Answered By: user10030086

Whenever you want to add key and value, you may want to use dict.update() method

Plus, as you wished to add key and value dynamically depending on user’s input, get value and key by splitting from user input

User shall input with space in between two values like below

key, value = input('input:').split()  #input: Hello 3

my_dict = {}
my_dict.update({key: value})

print(my_dict) #{"Hello" :3}
Answered By: Backrub32

Try the below code:

    n=int(input("enter a number of elements in the dict: "))
    my_dict = {}
    for i in range (n):
      key=input("Enter key :")
      value=input("Enter values :")
      my_dict.update({key: value})
    print(my_dict) 
Answered By: Anoop Bhatia

Thw best and simplest way here

n = int(input("Enter the no of entries you want to enter : "))
dict = {}
for i in range(n):
    key = int(input("Enter the key : " ))
    value = input("Enter the value : ")
    dict[key]=value
print(dict)
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.