Python:编辑字典键 - 使用 Strip 方法

标签 python dictionary str-replace key-value strip

我有一个字典,如下所示:

Dict = {' Chicago ': 4, ' Washington ': 9, ' LA ': 26, ' Boston ': 12, ' Seattle ': 2}

我想编辑每个条目的键,而不是值。您可以看到的键有一个在开头和结尾包含空格的字符串:' Chicago '、' Washington '、' LA '

我想分组并从键中去除空白。给我留下以下字典。

Dict = {'Chicago': 4, 'Washington': 9, 'LA': 26, 'Boston': 12, 'Seattle': 2}

我该怎么做?也许使用 replace("", "") 方法或 strip()

尝试 strip 方法时出现错误:

AttributeError: 'int' object has no attribute 'strip'

最佳答案

使用dict理解:

  • 顺便说一句,不要使用 python 数据类型作为变量的名称(例如 Dict)
  • Dict Comprehension
  • 当遍历字典时,可以使用 .items() 方法同时检索 key 和相应的 value
  • .strip仅在 key
data = {' Chicago ': 4, ' Washington ': 9, ' LA ': 26, ' Boston ': 12, ' Seattle ': 2}

data = {k.strip(): v for (k, v) in data.items()}

>>> {'Chicago': 4, 'Washington': 9, 'LA': 26, 'Boston': 12, 'Seattle': 2}

关于Python:编辑字典键 - 使用 Strip 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58551714/

相关文章:

php - 我过度使用 str_replace 并且想不出更好的方法

javascript - 在javascript中每次替换时增加一个数字

python - django 表单字段小部件中 3.35 版的 Google map API 问题

java - Android - 读取文本文件时内存不足

python - 排序和比较 Dicts Python 列表

c++ - uint16_t 到 uint16_t 映射的最高效容器

c++ - 使用 C++ 将一个字符串替换为另一个字符串

python - 如何使用 lldb 调试 C++ pybind11 模块?

Python自定义函数

python - 从python中的二进制文件中提取字符串