下面的函数append将一对不可变元组作为参数。在追加的处理中,必须将所有值都用单引号和结束引号引起来。因为元组值是不可变的,所以我不能简单地这样做:
if item[1][0] != "'" and item[1][-1] != "'":
item[1] = "'{0}'".format(item[1])
self.keyvalues[item[0]] = item[1]
因此处理如下:
if item[1][0] != "'" and item[1][-1] != "'":
self.keyvalues[item[0]] = "'{0}'".format(item[1])
else:
self.keyvalues[item[0]] = item[1]
完整的代码显示在下面。
是否有更优雅的方法将键和值添加到字典中。
class section(object):
"""class to hold a section. name is name of section. keyvalues is a key
value dictionary of keys and values"""
def __init__(self, name):
self.name = name
self.keyvalues = {}
print "Constructed section:", name
def append(self, item):
"""add a key value pair to section"""
if len(item) != 2:
return False
else:
print "adding:", item, "to", self.name, "object"
# cannot do this because tuple is immutable
#item[1] = "'{0}'".format(item[1])
# Would there be a more elegant way of doing this - given that
# parameter must be a immutable tuple?
if item[1][0] != "'" and item[1][-1] != "'":
self.keyvalues[item[0]] = "'{0}'".format(item[1])
else:
self.keyvalues[item[0]] = item[1]
return True
def __repr__(self):
s = "contains\n"
for k, v in self.keyvalues.iteritems():
s += "\t{0}={1}\n".format(k, v)
return s
__str__ = __repr__
mysection = section("section1")
dnpair = ("key1", "value1")
mysection.append(dnpair)
print mysection
由于不再使用元组,因此只需将其拆分为单独的变量即可。
key, value = item
if value[0] != "'" and value[-1] != "'":
value = "'{0}'".format(value)
self.keyvalues[key] = value
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句