有条件地添加到字典而不更新元组值

2024-09-22 14:31:19 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的函数append将一个不可变元组对作为参数。在处理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

Tags: andoftonameselfformatifis
2条回答

优雅是主观的,但这是我能想到的最优雅的解决方案。它允许通过将值传递给函数来进行值操作。也是丑陋的

if item[1][0] != "'" and item[1][-1] != "'":

变成

if not value[0] == value[-1] == "'":

下面是修改的append和新创建的quote_wrap方法的完整代码。你知道吗

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")
        self.keyvalues[item[0]] = self.quote_wrap(item[1])
        return True

def quote_wrap(self, value):
    if not value[0] == value[-1] == "'":
        value = "'{}'".format(value)
    return value

由于元组不再使用,所以只需将其拆分为单独的变量。你知道吗

key, value = item

if value[0] != "'" and value[-1] != "'":
    value = "'{0}'".format(value)

self.keyvalues[key] = value

相关问题 更多 >