尝试将值分配给字典中的键会产生类型错误

时间:2016-06-23 03:35:57

标签: python dictionary

字典[ “西北”] =(南+ width_NS,西)

TypeError:'type'对象不支持项目分配

class Building:
    def __init__(self, south, west, width_WE, width_NS, height=10):
      keys=("north-west","north-east","south-west","south-east")
      dict.fromkeys(keys)
      dict['north-west']=(south+width_NS,west)
      dict["north-east"]=(south+width_NS,west+width_WE)
      dict["south-west"]=(south,west)
      dict["south-east"]=(south,west+width_WE)
  self.corners=dict

2 个答案:

答案 0 :(得分:1)

您必须分配创建的词典:

d = dict.fromkeys(keys)

这给出了:

>>> d = dict.fromkeys(keys)
>>> d
{'south-west': None, 'south-east': None, 'north-east': None, 'north-west': None}
>>> d['north-west'] = (south+width_NS,west)
{'south-west': None, 'south-east': None, 'north-east': None, 'north-west': (6, 8)}

(我使用southwidth_NSwest的一些随机值

答案 1 :(得分:0)

使用另一个变量名称,例如dict1。这是正确的代码:

class Building:
    def __init__(self, south, west, width_WE, width_NS, height=10):
      keys=("north-west","north-east","south-west","south-east")
      dict1 = dict.fromkeys(keys)
      dict1['north-west']=(south+width_NS,west)
      dict1["north-east"]=(south+width_NS,west+width_WE)
      dict1["south-west"]=(south,west)
      dict1["south-east"]=(south,west+width_WE)
      self.corners=dict1