2013-05-07 50 views
2

我試圖擺脫價值名稱在迴應。請看下圖:Python刪除或更換密鑰

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, 
} 

回答

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

試試這個

def remove_sensitive(data): 
    for key,value in data.items(): 
     if key == "Name": 
      data[key] = "Not Stored!" 
    return data 
1

我會利用字典方法has_key()

def remove_sensitive(data): 
    if data.has_key("Name"): 
     data["Name"] = "Not Stored" 
    return data 
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