user input dictionary python code example

Example 1: how to take input for dictionary in python

for i in range(3):
    data = input().split(' ')
    d[data[0]] = int(data[1])

Example 2: how to input key and values to empty dictionary in python

>>> fruits = {}
>>> key1 = input("Enter first key for fruits:")
Enter first key for fruits:a
>>> value1 = input("Enter first value for fruits:")
Enter first value for fruits:apple
>>> key2 = input("Enter second key for fruits:")
Enter second key for fruits:b
>>> value2 = input("Enter second value for fruits:")
Enter second value for fruits:banana
>>> fruits[key1] = value1
>>> fruits
{'a': 'apple'}
>>> fruits[key2] = value2
>>> fruits
{'a': 'apple', 'b': 'banana'}
>>># Same variable names for keys and values can be used if used inside a loop like this
>>> fruits.clear()
>>> fruits
{}
>>> for i in range(2):
	key = input("Enter key for fruits:")
	value = input("Enter value for fruits:")
	fruits[key] = value
    
Enter key for fruits:a
Enter value for fruits:apple
Enter key for fruits:b
Enter value for fruits:banana
>>> fruits
{'a': 'apple', 'b': 'banana'}

Example 3: user input dictionary python

# Creates key, value for dict based on user input
# Combine with loops to avoid manual repetition
class_list = dict() 
data = input('Enter name & score separated by ":" ') 
temp = data.split(':') class_list[temp[0]] = int(temp[1])  

OR

key = input("Enter key") 
value = input("Enter value") 
class_list[key] = [value]

Example 4: python dictionary input

class_list = dict() data = input('Enter name & score separated by ":" ') temp = data.split(':') class_list[temp[0]] = int(temp[1])  # Displaying the dictionary for key, value in class_list.items(): 	print('Name: {}, Score: {}'.format(key, value))

Example 5: dictionary input from user in python3

d=dict(input().split() for x in range(n))
print(d)

Tags:

Misc Example