+ 1
How can i get input in a dictionary from user?
8 Respostas
+ 4
It breaks out of the loop when you enter an empty line. Good luck
dictionary={}
while True:
stuff=input("enter a string & integer")
if stuff=='':
break
else:
string=stuff.partition(' ')[0]
num=stuff.partition(' ')[2]
dictionary.update({string:int(num)})
continue
print(dictionary)
+ 4
Short time ago i have produced this:
The user can input a key (color name) and the 3 rgb values in a loop. you can input as many color / value pairs as you like. when you input x input loop breaks.
[Edit]: dict can be saved to a file in jason format if needed.
dic = {}
while True:
#dic.update({input('color: '):int(input('value: '))}) # 1 value
dic.update({input('color: '):list(map(int, input('3 values:').split(',')))}) # 3 values separated with comma
inp = input('x -> break, <RETURN> -> continue ')
if inp.upper() == 'X':
break
print(dic)
print(dic)
'''
output:
color: red
3 values:255,0,0
x -> break, <RETURN> -> continue
{'red': [255, 0, 0]}
color: green
3 values:0,255,0
x -> break, <RETURN> -> continue
{'red': [255, 0, 0], 'green': [0, 255, 0]}
color: blue
3 values:0,0,255
x -> break, <RETURN> -> continue x
{'red': [255, 0, 0], 'green': [0, 255, 0], 'blue': [0, 0, 255]}
'''
+ 2
Common way to do it is to provide dict in JSON format and parse it using json library. Like this:
import json
s = '{"name":"value"}'
my_dict = json.loads(s)
print my_dict
Of course you can replace s with other things like raw_input() or what ever function you use that returns string.
+ 1
Can you describe more explicitly what you want to do?
+ 1
I am a beginner so i am just practing this... I want to map strings with numbers that should be given by the user as inputs like
Input:
Some 55
got 66
Output:
{ "Some" : 55 , "got" : 66}
+ 1
Thanks
0
Ùۧ۟ ۧÙŰȘÙ ŰčÙۧÙ
ۧŰȘ ÙŰŻÙÙÙ
ۧÙŰčۧÙÙÙ
0
you can use the below method to input user data in dictionary
student = {}
student.update({'car' : 'Toyota'})
print(student)
while True:
x = input()
y = input()
if x and y != '/':
student.update({x : y})
else:
break
print(student)