【问题标题】:Tuple (key, value) to dictionary ValueError: dictionary update sequence element #0 has length 6; 2 is required元组(键,值)到字典 ValueError:字典更新序列元素 #0 的长度为 6; 2 是必需的
【发布时间】:2018-10-22 18:07:48
【问题描述】:

我有一个字符串,我正则表达式返回一个元组(查看打印的结果),我想从中创建一个字典(元组的第一个条目是键,第二个是值),根据 StackOverflow 帖子应该像一种魅力。 for 循环可以返回多个点,每个点都应添加到应返回的单个 dict 中。

代码和错误:

import re as re

n = nuke.selectedNode()
k = n.knob('scene')
script = k.toScript().replace('\n','').split('scenegraph {')

for sgrph in script:
    for m in [re.match(r".*\bname '([Point\d]+)'.*\btransform ([0-9.e+\- ]+)",sgrph)]:
        if m is not None:
            print m.groups()
            items = dict(m.groups()) #this causes the error
            print "........."
print items

输出:

# Result: ('Point1', '1.983990908e+00 0.000000000e+00 0.000000000e+00 0.000000000e+00 0.000000000e+00 1.983990908e+00 0.000000000e+00 0.000000000e+00 0.000000000e+00 0.000000000e+00 1.983990908e+00 0.000000000e+00 5.610483289e-01 6.365304199e+03 4.553408813e+02 1.000000000e+00      ')
    Traceback (most recent call last):
      File "<string>", line 11, in <module>
    ValueError: dictionary update sequence element #0 has length 6; 2 is required

【问题讨论】:

    标签: python dictionary tuples


    【解决方案1】:

    python 中的字典可以从 (key, value) 对的迭代中创建。但是由于m.groups() 调用,您有一个扁平的值元组。你需要选择这个元组的偶数元素作为键,然后选择奇数元素作为对应的值,然后zip它们一起:

    values = ('foo', 'bar', 'qux', 'blah')
    dict(zip(values[::2], values[1::2]))
    

    这里是一个使用re.match().groups()的例子:

    import re
    match = re.match(r'(\d+) (\d+) (\d+) (\d+)', '12 34 56 78')
    groups = match.groups()               # gives ('12', '34', '56', '78')
    dict(zip(groups[::2], groups[1::2]))  # gives {'56': '78', '12': '34'}
    

    UPD:请注意,zip 生成的序列的长度被截断为其输入的最短长度。因此,如果m.groups() 返回奇数个元素,则最后一个值将不会出现在结果字典中。

    【讨论】:

      【解决方案2】:

      在我看来,明确表达是个好主意。例如,您可以在嵌套的 for 循环之前定义您的字典,显式解包并将一个项目添加到您的字典中。

      res = {}
      
      for sgrph in script:
          for m in [re.match(r".*\bname '([Point\d]+)'.*\btransform ([0-9.e+\- ]+)",sgrph)]:
              if m is not None:
                  key, value = m.groups()
                  res[key] = value
      

      【讨论】:

      • 感谢您的帮助。这是一种干净且有效的方法。
      猜你喜欢
      • 2021-04-01
      • 2016-06-30
      • 2015-02-22
      • 2019-08-10
      • 2017-12-27
      • 1970-01-01
      • 1970-01-01
      • 2016-02-17
      相关资源
      最近更新 更多