📜  Python|从字典键中删除空格

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

Python|从字典键中删除空格

在Python中,字典是一个无序、可变和索引的集合。字典是用大括号写的,它们有键和值。它用于散列特定的密钥。

让我们看看如何从Python中的字典键中删除空格。

方法#1:
在这里使用translate()函数,我们一个一个地访问每个键,并删除没有空格的空格。这里 translate函数采用参数 32,none ,其中 32 是空格 ' ' 的 ASCII 值,并将其替换为 none。

# Python program to remove space from keys
  
# creating a dictionary of type string
  
Product_list = {'P 01' : 'DBMS', 'P 02' : 'OS',
                'P 0 3 ': 'Soft Computing'}
  
# removing spaces from keys
# storing them in sam dictionary
Product_list = { x.translate({32:None}) : y 
                 for x, y in Product_list.items()}
  
# printing new dictionary
print (" New dictionary : ", Product_list)
输出:
New dictionary :  {'P01': 'DBMS', 'P03': 'Soft Computing', 'P02': 'OS'}


方法#2:
使用replace()函数。在这种方法中,我们一个一个地访问字典中的每个键,并将键中的所有空格替换为没有空格。此函数作为参数空间和第二个非空间。

# Python program to remove space from keys
  
# creating a dictionary of type string
  
Product_list = {'P 01' : 'DBMS', 'P 02' : 'OS',
                'P 0 3 ': 'Soft Computing'};
  
# removing spaces from keys
# storing them in sam dictionary
Product_list = {x.replace(' ', ''): v 
     for x, v in Product_list.items()}
  
# printing new dictionary
print (" New dictionary : ", Product_list)
输出:
New dictionary :  {'P03': 'Soft Computing', 'P01': 'DBMS', 'P02': 'OS'}