我有一本像下面這樣的字典:
{
'file1.txt': {'address': [], 'ORG': []},
'file2.txt': {'address': [], 'ORG': ['DEF Pvt. Ltd','One Solutions (Asia) Limited' ]}
}
我需要從“ORG”鍵中洗掉特殊字符。
我知道我們可以做一本普通的字典{key.strip(): item.strip() for key, item in my_dict.items()}
但我不確定如何為嵌套的人做這件事,有什么想法嗎?
uj5u.com熱心網友回復:
你可以這樣做:
for key, value in my_dict.items():
my_dict['key'] = [char for char not in list_special]
這里,list_special 是一個特殊字串列。
如果它是字典中的串列,則必須添加嵌套的 for 回圈。
uj5u.com熱心網友回復:
根據ORG鍵中元素的未知數量,我非常喜歡使用兩個 for 回圈和正則運算式。
因此,您需要匯入regex庫,然后使用re.sub可以洗掉特定字符的庫。
我在這個問題中使用的正則運算式是:
[^a-zA-Z\d\s:]
整個腳本:
import re
myDict = {
'file1.txt': {'address': [], 'ORG': []},
'file2.txt': {'address': [], 'ORG': ['DEF Pvt. Ltd','One Solutions (Asia) Limited' ]}
}
for key, item in myDict.items():
tempList = myDict[key]["ORG"]
for index, value in enumerate(tempList):
tempList[index] = re.sub(r"[^a-zA-Z\d\s:]", "", value)
myDict[key]["ORG"] = tempList
print(myDict)
輸出:
{
'file1.txt': {'address': [], 'ORG': []},
'file2.txt': {'address': [], 'ORG': ['DEF Pvt Ltd', 'One Solutions Asia Limited']}
}
uj5u.com熱心網友回復:
根據我之前的評論,這里有一個有效的解決方案,無論嵌套字典的深度如何,也沒有任何硬編碼的鍵名:
原碼
修改后的代碼:
import re
def change_dict_naming_convention(d, convert_function):
"""
Convert a nested dictionary from one convention to another.
Args:
d (dict): dictionary (nested or not) to be converted.
convert_function (func): function that takes the string in one convention and returns it in the other one.
Returns:
Dictionary with the new keys.
"""
if isinstance(d, dict):
new = {}
for k, v in d.items():
new_v = v
if isinstance(v, dict):
new_v = change_dict_naming_convention(v, convert_function)
elif isinstance(v, list):
new_v = list()
for x in v:
new_v.append(change_dict_naming_convention(x, convert_function))
elif isinstance(v, str):
new_v = convert_function(v)
new[convert_function(k)] = new_v
elif isinstance(d, str):
new = convert_function(d)
else:
new = d
return new
def convert_function(value):
return re.sub(r"[^a-zA-Z\d\s\.:]", "", value)
orignial_dict: dict = {
'file1.txt': {'address': {'street': 'Any Street No. 22 (a)',
'zipCode': 1234,
'city': 'AnyCity (Asia)'},
'ORG': ['123 (DEF) #Pvt. -Ltd','One Solutions (Asia) Limited']},
'file2.txt': {'address': [],
'ORG': ['DEF Pvt. Ltd','One Solutions (Asia) Limited' ]}
}
new_dict: dict = change_dict_naming_convention(orignial_dict, convert_function)
print(new_dict)
輸出:
{'file1.txt': {'address': {'street': 'Any Street No. 22 a', 'zipCode': 1234, 'city': 'AnyCity Asia'}, 'ORG': ['123 DEF Pvt. Ltd', 'One Solutions Asia Limited']},
'file2.txt': {'address': [], 'ORG': ['DEF Pvt. Ltd', 'One Solutions Asia Limited']}}
我希望這可以幫助你 ;)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/338843.html
下一篇:華為地圖套件樣式功能
