如何修改和删除Python2字典中的特殊字符

时间:2018-01-14 18:41:55

标签: python json dictionary unicode key

我正在尝试删除Python字典键中的特殊字符,并在该年份存在的情况下将密钥的year添加到其对应的value

{'New Year Day 2019\\xa0': 'Tuesday, January 1', 'Good Friday': 'Friday, March 30', 'New Year Day 2018\\xa0': 'Monday, January 1'}

键和值都是字符串。我希望它看起来如下:

{'New Year Day': 'Tuesday, January 1, 2019', 'Good Friday': 'Friday, March 30', 'New Year Day': 'Monday, January 1, 2018'}

我尝试删除\xa0,但未成功:

    for key in data:
        key.replace('\xa0', '')
        print key

我想我需要使用(re.search(r'[12]\d{3}', key)).group[0]正则表达式获得年份。但是如何将其从按键中删除?

2 个答案:

答案 0 :(得分:0)

您可以重命名value个密钥,添加新的key添加删除旧密钥:

dic = {'New Year Day 2019\\xa0': 'Tuesday, January 1', 'Good Friday': 'Friday, March 30', 'New Year Day 2018\\xa0': 'Monday, January 1'}

for key in dic:
    if key != key.replace('\\xa0', ''):
        dic[key.replace('\\xa0', '')] = dic[key]
        del dic[key]

print(dic)

结果将是:

{'Good Friday': 'Friday, March 30', 'New Year Day 2019': 'Tuesday, January 1', 'New Year Day 2018': 'Monday, January 1'}

答案 1 :(得分:0)

如果是特殊字符“\ xa0”,您试图从键中删除,请尝试以下操作:

data = {'New Year Day 2019\\xa0': 'Tuesday, January 1', 'Good Friday': 'Friday, March 30', 'New Year Day 2018\\xa0': 'Monday, January 1'}
for i in data:
    if "\\xa0" in i:
        data[i.replace("\\xa0", "")] = data.pop(i)
print data

希望这会有所帮助。