【问题标题】:How to assign values to keys如何为键赋值
【发布时间】:2012-08-25 01:12:44
【问题描述】:

当我执行以下操作时出现“不可散列”错误:

a = {}
a["wer":"table.%%maker%%"]

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    a["wer":"table.%%maker%%"]
TypeError: unhashable type

“wer”键在这里应该有“table.%maker%”的值,但我不能插入百分号。我该怎么办?

【问题讨论】:

标签: python string dictionary


【解决方案1】:

您可以在字典的构造(init)期间设置值:

a = {"wer":"table.%%maker%%"}

或者在构造字典之后,使用下标操作符:

a = {}
a["wer"] = "table.%%maker%%"

【讨论】:

    【解决方案2】:

    使用它为“wer”键分配值:

    a["wer"] = "table.%%maker%%"
    

    【讨论】:

      【解决方案3】:

      您可以在字典键中使用 % 字符,但是您分配的值是错误的。

      >>> my_dict = {} 
      >>> my_dict['wer'] = 'table.%maker%'
      >>> my_dict
      {'wer': 'table.%maker%'}
      

      您可以将符号与 : 一起使用,如下所示:

      >>> my_dict = {'wer': 'table.%maker%'}
      >>> my_dict
      {'wer': 'table.%maker%'}
      

      Python 有一个很棒的文档来描述如何使用数据结构 here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-18
        • 2011-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多