【问题标题】:convert all the values in a dictionary to strings将字典中的所有值转换为字符串
【发布时间】:2021-08-08 12:50:09
【问题描述】:

假设我有一个包含字符串和整数作为值的字典的混合列表,我想将整数转换为字符串,考虑到列表是流动的,应该如何做到这一点,而不是到处走动并一一转换, long 并且还可能将一些现有值更改为整数。

示例:

list = [{'a':'p', 'b':2, 'c':'k'},
        {'a':'e', 'b':'f', 'c':5}]

现在,如果我尝试用字符串打印列表的值,它会给我一个错误,如下所示。

示例:

for x in list:
    print('the values of b are: '+x['b'])

输出:

TypeError: can only concatenate str (not "int") to str

Process finished with exit code 1

感谢任何帮助,谢谢!

解决方案

list = [{'a':'p', 'b':2, 'c':'k'},
        {'a':'e', 'b':'f', 'c':5}]

for dicts in list:
    for keys in dicts:
        dicts[keys] = str(dicts[keys])
print('the valuse of b are: '+ dicts["b"])

【问题讨论】:

  • 您希望这些项目永久为字符串吗?否则你可以用 str(x['b']) 包裹 x['b']
  • 感谢它的工作!我的错误是我之前试图做一些不同的事情,就像这样:(x[str('b')])
  • 太好了,让我仍然指向我的答案,如果您需要更通用的解决方案来始终获取字符串,无论输入什么样的值

标签: python python-3.x list dictionary type-conversion


【解决方案1】:

如果要将字典值转换为字符串然后打印:

list = [{'a':'p', 'b':2, 'c':'k'}, {'a':'e', 'b':'f', 'c':5}]
list = [{str(j): str(i) for i, j in enumerate(d)} for d in list]

for x in list:
    print("the values of b is: " + x['b'])

如果您只想打印而不更改:

for x in list:
    print(f"the values of b is: {x['b']}")

【讨论】:

  • 谢谢,但是为了让 'f' 函数起作用,你必须使用双引号
  • 哦,谢谢指出!现在编辑它。
【解决方案2】:

其他解决方案都一次性转换为字符串,但是,当您无法控制这些值是否随后被改回时,这无济于事。

我建议这样子类化dict:

class StringDict(dict):
    def __init__(self):
        dict.__init__(self)
        
    def __getitem__(self, y):
        value_to_string = str(dict.__getitem__(self, y))
        return value_to_string
    
    def get(self, y):
        value_to_string = str(dict.get(self, y))
        return value_to_string
    
    

exampleDict = StringDict()

exampleDict["no_string"] = 123

print(exampleDict["no_string"])
123
print(type(exampleDict["no_string"]))
<class 'str'>

这样,值类型不会改变,但在访问时会立即转换为字符串,保证返回一个字符串

【讨论】:

  • 老实说,我几乎不懂你的代码,我想这对我的水平来说有点太多了,但因为我只是在学习并尽可能多地理解我已经复制了你的代码和我最关心的是最后一行&lt;class 'str'&gt;,因为我从未见过以这种方式实现这些标签,而且解释器告诉我这种语法不正确......是吗?
  • 嘿,不用担心。可以省略最后一行和倒数第三行。它们只是打印输出
  • 这段代码的基本作用是采用标准字典并覆盖 get 函数以始终返回字符串。因此,当您将 int 123 添加到 dict 然后获取它时,您会得到 '123' 而无需转换它
【解决方案3】:

为什么不:

print(f"The value of b is: {x['b']}")

【讨论】:

    【解决方案4】:

    试试这个

    list = [{'a':'p', 'b':2, 'c':'k'},
            {'a':'e', 'b':'f', 'c':5}]
    
    for dicts in list:
        for keys in dicts:
            dicts[keys] = str(dicts[keys])
    print(list)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      • 2013-09-23
      • 2021-07-25
      相关资源
      最近更新 更多