如何覆盖python字典值?

时间:2012-08-13 19:24:13

标签: python dictionary overwrite

简化我的词典:

my_dict = {
    'DOC': [
        [('k', 'v'), ('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3'), ('k4', 'v4')],
        [('k5', 'v5'), ('k', 'v'), ('k1', 'v1'), ('k6', 'v6')]
    ],
    'DIC': [
        [('k7', 'v7'), ('k3', 'v3'), ('k8', 'v8')],
        [('k5', 'v5'), ('k3', 'v3'), ('k1', 'v1'), ('k2', 'v2')],
        [('k4', 'v4'), ('k9', 'v9')]
    ],
    'INFRA': [
        [('k5', 'v5'), ('k3', 'v3'), ('k1', 'v1'), ('k2', 'v2')],
        [('k', 'v'), ('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3'), ('k4', 'v4')]
    ]
}

覆盖我的字典值:

for k, v in my_dict.items():
     my_dict[k] = map(lambda x: dict(x), my_dict[k])

...返回

my_dict 
{'DIC': [{'k3': 'v3', 'k7': 'v7', 'k8': 'v8'},
         {'k1': 'v1', 'k2': 'v2', 'k3': 'v3', 'k5': 'v5'},
         {'k4': 'v4', 'k9': 'v9'}],
 'DOC': [{'k': 'v', 'k1': 'v1', 'k2': 'v2', 'k3': 'v3', 'k4': 'v4'},
         {'k': 'v', 'k1': 'v1', 'k5': 'v5', 'k6': 'v6'}],
 'INFRA': [{'k1': 'v1', 'k2': 'v2', 'k3': 'v3', 'k5': 'v5'},
           {'k': 'v', 'k1': 'v1', 'k2': 'v2', 'k3': 'v3', 'k4': 'v4'}]}

当我按照相同的逻辑运行我的实际代码时,我得到了错误:

  

ValueError:字典更新序列元素#0的长度为6; 2是必需的

我尝试创建另一个字典来接收map(),但发生了同样的错误。有人可以帮帮我吗?

5 个答案:

答案 0 :(得分:4)

真实测试用例中的输入不符合您期望的结构。特别是,不是所有元组都是元组,至少有一个元素是长度为6的序列。例如,错误输入可能看起来像:

{'DOC': [
    [('123456')],               # A string is a sequence, too
    [('123' '456')]             # Note the lack of a comma
    [('1','2','3','4','5','6')] # A tuple, but with 6 elements
    [['1','2','3','4','5','6']] # A list
]}

要解决此问题,请检查您的输入,例如:

for k, v in my_dict.items():
    for l in v:
        for subl in v:
            for tup in subl:
                if not len(tup) == 2:
                    raise ValueError('In %r: value is not a tuple(2), but %r'
                                     % (k, tup))

哦,顺便说一句,在设计数据结构时,遵循Zen of Python通常是个好主意,其中包括:

  

Flat比嵌套好。

答案 1 :(得分:1)

dict构造函数需要一系列2项子序列(列表或元组)。至少有一个子序列包含两个以上的项目。

也许您缺少逗号(参见最后一项):

>>> dict([('1', 'red'),('2', 'blue'),('3' 'purple')]) # missing comma in last item
Traceback (most recent call last):
  File "<pyshell#166>", line 1, in <module>
    dict([('1', 'red'),('2', 'blue'),('3' 'purple')]) 
ValueError: dictionary update sequence element #2 has length 7; 2 is required

或者也许是单个项目而不是元组(再次参见最后一项)

>>> dict([('1', 'red'),('2', 'blue'),('purple')]) # last "tuple" has one item
Traceback (most recent call last):
  File "<pyshell#167>", line 1, in <module>
    dict([('1', 'red'),('2', 'blue'),('purple')])
ValueError: dictionary update sequence element #2 has length 6; 2 is required

答案 2 :(得分:0)

问题在于,在你的“真实代码”中,你的一个列表的第一个元素有两个以上的元素(6)。 dict只需要两个就可以将它们解释为key, value

以下是生成您描述的错误的示例:

my_dict = {
    'DOC': [
        [('k', 'v', 'extra1', 'extra2', 'extra3', 'extra4'), ('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3'), ('k4', 'v4')],
        [('k5', 'v5'), ('k', 'v'), ('k1', 'v1'), ('k6', 'v6')]
    ],
    'DIC': [
        [('k7', 'v7'), ('k3', 'v3'), ('k8', 'v8')],
        [('k5', 'v5'), ('k3', 'v3'), ('k1', 'v1'), ('k2', 'v2')],
        [('k4', 'v4'), ('k9', 'v9')]
    ],
    'INFRA': [
        [('k5', 'v5'), ('k3', 'v3'), ('k1', 'v1'), ('k2', 'v2')],
        [('k', 'v'), ('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3'), ('k4', 'v4')]
    ]
}

这是一种放入print语句以查看问题元素的简单方法:

for k, v in my_dict.items():

    # Print out the first element of each list,
    # because one of them has six elements when it should only have two.
    for l in my_dict[k]:
        print l[0]

    my_dict[k] = map(lambda x: dict(x), my_dict[k])

答案 3 :(得分:0)

我可以看到您的问题中的代码和数据没有问题。假设“真实”代码没有什么显着不同,你可以做这样的事情来找出导致错误发生的格式错误的数据:

def test(x):
    print x
    return dict(x)

for k, v in my_dict.items():
#     my_dict[k] = map(lambda x: dict(x), my_dict[k])
     my_dict[k] = map(test, my_dict[k])

答案 4 :(得分:-1)

这段代码比你的简单得多:

temp_dict = {}
for k in my_dict():
    temp_dict[k] = {}
    for t in my_dict[k]:
        temp_dict[k][t[0]] = t[1]
my_dict = temp_dec
del temp_dec