Issue
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.
Solution
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 value\n"))
desiredDict[key] = valList
return desiredDict
Answered By - user10030086
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.