简体   繁体   English

如何覆盖python字典值?

[英]How to overwrite python dictionary values?

A simplification of my dictionary: 简化我的字典:

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')]
    ]
}

Overwriting my dictionary values: 覆盖我的字典值:

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

Returning... 返回...

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'}]}

When I ran my real code following the same logic I got the error: 当我按照相同的逻辑运行我的实际代码时,我得到了错误:

ValueError: dictionary update sequence element #0 has length 6; ValueError:字典更新序列元素#0的长度为6; 2 is required 2是必需的

I've tried to create another dictionary to receive the map() but the same error occurred. 我试图创建另一个字典来接收map()但发生了同样的错误。 Someone could help me? 有人可以帮帮我吗?

The input in the real testcase doesn't conform to the structure you expect. 真实测试用例中的输入不符合您期望的结构。 In particular, instead of all being tuples, at least one of the elements is a sequence of length 6. For example, a faulty input may look like: 特别是,不是所有元素都是元组,至少有一个元素是长度为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
]}

To solve this problem, check your input, like: 要解决此问题,请检查您的输入,例如:

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))

Oh, by the way, when designing data structures, it's often a good idea to follow the Zen of Python , which includes: 哦,顺便说一句,在设计数据结构时,遵循PythonZen通常是一个好主意,其中包括:

Flat is better than nested. Flat优于嵌套。

The dict constructor expects a sequence of 2 item subsequences (lists or tuples). dict构造函数需要一个包含2 dict项子序列(列表或元组)的序列。 At least one of subsequences contains more then two items. 至少有一个子序列包含两个以上的项目。

Perhaps you have missing comma (see last item): 也许你错过了逗号(见最后一项):

>>> 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

Or maybe a single item instead of a tuple (again, see last item) 或者也许是单个项目而不是元组(再次参见最后一项)

>>> 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

The problem is that in your "real code", the first element of one of your lists has more than two elements (6). 问题是,在你的“真实代码”中,你的一个列表的第一个元素有两个以上的元素(6)。 dict requires exactly two to interpret them as key, value . dict需要两个就可以将它们解释为key, value

Here's an example that generates the error you describe: 这是一个生成您描述的错误的示例:

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')]
    ]
}

Here's a simple way to drop in a print statement to see the problem element: 这是一个简单的方法来放入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])

I can see no problem with code and data in your question. 我可以看到你的问题中的代码和数据没有问题。 Assuming there's nothing significantly different about the "real" code, you could do something like this to find out what the malformed data is that causes the error to occur: 假设“真实”代码没有什么显着不同,你可以做这样的事情来找出导致错误发生的格式错误的数据:

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])

How about this code which is simpler than yours: 这个代码比你的简单怎么样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM