向用户询问字符串并创建以下字典:值是字符串中的字母,相应的键是字符串中的位置。例如,如果用户输入字符串CSC120
,则创建字典d
。
d = { 0:'C', 1:'S', 2:'C', 3:'1', 4:'2', 5:'0'}
答案 0 :(得分:2)
对dict
的结果使用enumerate
函数:
s = "CSC120"
result = dict(enumerate(s))
print(result)
# {0: 'C', 1: 'S', 2: 'C', 3: '1', 4: '2', 5: '0'}
答案 1 :(得分:0)
userStr=input("please enter a word") # asking the user to enter a string
d={} # initialize an empty dictionary "d"
# looping through the value of userStr by each index of letter in userStr # and the letter itself.
for i,letter in enumerate(userStr):
d[i]=letter # adding a key and value in the dictionary "d"
print(d) # printing the dictionary "d"