下面的函数附加了一对作为参数的不可变元组。在追加处理中,有必要用开始和结束单引号括起所有值。因为元组值是不可变的,我不能简单地这样做:在不更新元组值的情况下有条件地添加到字典
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
你这样做的方式很好。 “优雅”解决方案纯粹是一种主观基础。 – 2014-11-06 16:16:05
@StackofPancakes可能是的,但我对Python比较陌生,所以想知道如果我错过了一些有用的想法 – 2014-11-06 16:18:44