我正试图在响应中删除值名称。见下文:
response_data_all_details = decode_transaction_response(response.text)
# Remove and sensitive information we don't want to be stored in the database.
response_data = remove_sensitive(response_data_all_details)
功能:如果响应中有名称,请将其替换为“未存储”文字。
def remove_sensitive(data):
for key in data:
if data[key] == "Name":
data['Name'] = "Not Stored!"
return data
但是,这个功能似乎不起作用,为什么?
示例response_data
{
"URL" : "http:\/\/www.test.com",
"Name" : "James",
"Currency" : "GBP",
"Amount" : 5.880000000000001,
}
答案 0 :(得分:2)
这里的一个简单解决方案是使用:if key in data
def remove_sensitive(data,key):
if key in data:
data[key] = "Not Stored!"
return data
修复您的代码:
您必须使用if key == "Name":
:
def remove_sensitive(data):
for key in data:
if key == "Name":
data[key] = "Not Stored!"
return data
那是因为对字典的迭代会逐个产生密钥:
>>> for key in data:
... print key
...
URL
Currency
Amount
Name
演示:
def remove_sensitive(data):
for key in data:
if key == "Name":
data[key] = "Not Stored!"
return data
>>> data = {
"URL" : "http:\/\/www.test.com",
"Name" : "James",
"Currency" : "GBP",
"Amount" : 5.880000000000001,
}
>>> remove_sensitive(data)
{'URL': 'http:\\/\\/www.test.com',
'Currency': 'GBP',
'Amount': 5.880000000000001,
'Name': 'Not Stored!'}
答案 1 :(得分:2)
你太复杂了。这应该有效:
def remove_sensitive(data):
data['Name'] = "Not Stored!"
return data
或者,如果您不确定密钥'Name'
是否存在:
def remove_sensitive(data):
if data.has_key('Name'):
data['Name'] = "Not Stored!"
return data
答案 2 :(得分:1)
试试这个
def remove_sensitive(data):
for key,value in data.items():
if key == "Name":
data[key] = "Not Stored!"
return data
答案 3 :(得分:1)
我会使用dict方法has_key()
def remove_sensitive(data):
if data.has_key("Name"):
data["Name"] = "Not Stored"
return data