从 Python 中的字典键中删除空格
Python 中要从字典中的键中删除空格:
- 使用字典推导来迭代字典。
- 使用 str.replace() 方法从每个键中删除空格。
- 从字典推导中返回新的键和值。
my_dict = {
'o n e': 1,
't w o': 2,
't h r e e': 3
}
# ✅ 从字典键中删除空格(使用字典推导)
new_dict = {
key.replace(' ', ''): value for key, value in my_dict.items()
}
# ?️ {'one': 1, 'two': 2, 'three': 3}
print(new_dict)
print(new_dict['one']) # ?️ 1
print(new_dict['two']) # ?️ 2
# -------------------------------------------------------
# ✅ 从字典键中删除空格 (使用for循环)
new_dict = {}
for key, value in my_dict.items():
new_dict[key.replace(' ', '')] = value
# ?️ {'one': 1, 'two': 2, 'three': 3}
print(new_dict)
print(new_dict['one']) # ?️ 1
print(new_dict['two']) # ?️ 2
第一个示例使用字典推导从字典中的键中删除空格。
字典推导与列表推导非常相似。
my_dict = {
'o n e': 1,
't w o': 2,
't h r e e': 3
}
new_dict = {
key.replace(' ', ''): value for key, value in my_dict.items()
}
# ?️ {'one': 1, 'two': 2, 'three': 3}
print(new_dict)
dict.items() 方法返回字典项目((key, value)对)的新视图。
my_dict = {
'o n e': 1,
't w o': 2,
't h r e e': 3
}
# ?️ dict_items([('o n e', 1), ('t w o', 2), ('t h r e e', 3)])
print(my_dict.items())
在每次迭代中,我们使用 str.replace() 方法从当前键中删除空格并返回键值对。
str.replace() 方法返回字符串的副本,其中所有出现的子字符串都被提供的替换替换。
该方法采用以下参数:
- old 字符串中我们要替换的子字符串
- new 每次出现 old 的替换
- count 仅替换第一个 count 事件(可选)
或者,可以使用简单的 for 循环。
使用 for 循环从字典键中删除空格
要从字典中的键中删除空格:
- 使用 for 循环遍历字典。
- 使用 str.replace() 方法从每个键中删除空格。
- 将每个键值对添加到新字典中。
my_dict = {
'o n e': 1,
't w o': 2,
't h r e e': 3
}
new_dict = {}
for key, value in my_dict.items():
new_dict[key.replace(' ', '')] = value
# ?️ {'one': 1, 'two': 2, 'three': 3}
print(new_dict)
print(new_dict['one']) # ?️ 1
print(new_dict['two']) # ?️ 2
我们声明了一个 new_dict 变量,它将存储键不包含空格的键值对。
在每次迭代中,我们使用 str.replace() 方法从当前键中删除空格并将键值对分配给新字典。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。