假设我有一个python字典如下:
myDict = {"I need you to call the doctor please.":
"I'm sorry, Dave. I'm afraid I can't do that."}
但是,如果我将一个名为myName
的变量设置为等于"XYZ"
,我希望它只输出:
"I'm sorry, XYZ. I'm afraid I can't do that."
我很好奇如何设置字典值呢?
答案 0 :(得分:3)
但是你做到了,从字典中提取后,你必须做一些额外的事情。
您可以将格式字符串存储为您的值:
name = 'Dave'
myDict = {
'I need you to call the doctor please.':
"I'm sorry, {name}. I'm afraid I can't do that."
}
提取值后,您可以将格式参数传递给str.format
:
myDict['I need you to call the doctor please.'].format(name=name)
您还可以使用旧式格式:
"I'm sorry, %(name). I'm afraid I can't do that." % {'name':
名称}
未命名的参数也可以使用:
"I'm sorry, {}. I'm afraid I can't do that.".format(name)
"I'm sorry, %s. I'm afraid I can't do that." % name
答案 1 :(得分:2)
假设名称在字典值中只出现一次
myDict = {"I need you to call the doctor please.": "I'm sorry, Dave. I'm afraid I can't do that."}
name = "Dave"
myName = "XYZ"
myDict["I need you to call the doctor please."].replace(name, myName)
输出
"I'm sorry, XYZ. I'm afraid I can't do that."
使其成为n
名称
myDict = {
"I need you to call the doctor please.": "I'm sorry, Dave. I'm afraid I can't do that.",
"I want you to call the Mad Physicist please.": "I'm sorry, Mad Physicist. I'm afraid I can't do that."
}
names = ["Dave", "Mad Physicist"]
replacement = ["XYZ", "Van Peer"]
i=0
for x in myDict:
myDict[x] = myDict[x].replace(names[i],replacement[i])
i+=1
print(myDict)
输出
{
'I need you to call the doctor please.': "I'm sorry, XYZ. I'm afraid I can't do that.",
'I want you to call the Mad Physicist please.': "I'm sorry, Van Peer. I'm afraid I can't do that."
}
答案 2 :(得分:0)
def name():
name = raw_input("What is your name: ")
myDict = {"I need you to call the doctor please.": "I'm sorry, " + name + ". I'm afraid I can't do that."}
print myDict
这就是你要做的。