📌  相关文章
📜  Python – 从字典键中删除双引号

📅  最后修改于: 2022-05-13 01:55:12.292000             🧑  作者: Mango

Python – 从字典键中删除双引号

给定带有字符串键的字典,从中删除双引号。

方法#1:使用字典理解+replace()

以上功能的组合可以用来解决这个问题。在这种情况下,我们使用带有空字符串的 replace() 去除双引号。字典理解用于重新制作字典。

Python3
# Python3 code to demonstrate working of
# Remove double quotes from dictionary keys
# Using dictionary comprehension + replace()
 
# initializing dictionary
test_dict = {'"Geeks"' : 3, '"is" for' : 5, '"g"eeks' : 9}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# dictionary comprehension to make double quotes free
# dictionary
res = {key.replace('"', ''):val for key, val in test_dict.items()}
     
# printing result
print("The dictionary after removal of double quotes : " + str(res))


Python3
# Python3 code to demonstrate working of
# Remove double quotes from dictionary keys
# Using re.sub() + dictionary comprehension
import re
 
# initializing dictionary
test_dict = {'"Geeks"' : 3, '"is" for' : 5, '"g"eeks' : 9}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# regex making replacement of double quotes with empty string
res = {re.sub(r'"', '', key): val for key, val in test_dict.items()}
     
# printing result
print("The dictionary after removal of double quotes : " + str(res))


输出
The original dictionary is : {'"Geeks"': 3, '"is" for': 5, '"g"eeks': 9}
The dictionary after removal of double quotes : {'Geeks': 3, 'is for': 5, 'geeks': 9}

方法 #2:使用 re.sub() + 字典理解

上述功能的组合也是解决此任务的另一种选择。在这里,我们使用正则表达式来解决问题。

蟒蛇3

# Python3 code to demonstrate working of
# Remove double quotes from dictionary keys
# Using re.sub() + dictionary comprehension
import re
 
# initializing dictionary
test_dict = {'"Geeks"' : 3, '"is" for' : 5, '"g"eeks' : 9}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# regex making replacement of double quotes with empty string
res = {re.sub(r'"', '', key): val for key, val in test_dict.items()}
     
# printing result
print("The dictionary after removal of double quotes : " + str(res))
输出
The original dictionary is : {'"Geeks"': 3, '"is" for': 5, '"g"eeks': 9}
The dictionary after removal of double quotes : {'Geeks': 3, 'is for': 5, 'geeks': 9}