Skip to main content
 首页 » 编程设计

python之编写此 block 的更多 pythonic 方式(并删除 : ValueError: dictionary update sequence element #0 has length 1; 2 is required)

2025年05月04日85birdshome

我有这个(有效):

def make_key(x): 
    return "{0}/{1}/{2}".format(x.f1, x.f2, x.f3) 
 
def make_value(x): 
    return (x.f7, x.f1, x.f4, x.f9,  
            x.f2, x.f8, x.f10, x.f11, x.f12, x.f17,  
            x.f18, x.f19, x.f14, x.f15, 
            x.f16, x.f17, x.f20) 
 
row_data = {} 
    for x in records: 
        key = make_key(x.f1,x.f2,x.f3) 
        value = make_value(x) 
        row_data[key] = value     

我试过这个:

row_data = dict([(make_key(x), make_value(x))] for x in records) 

我收到这个错误:

ValueError: dictionary update sequence element #0 has length 1; 2 is required 

编辑:

records 是具有字段属性 f1, ...fn

的对象列表

请您参考如下方法:

您需要删除列表包装器;只生成元组:

row_data = dict((make_key(x), make_value(x)) for x in records) 

您正在生成一个列表,每个元素都有一个元素,一个元组。

如果您使用的是 Python 2.7 或更新版本,您还可以使用字典理解:

row_data = {make_key(x): make_value(x) for x in records} 

您的 make_value 可以使用 operator.itemgetter() object 表示:

from operator import itemgetter 
 
make_value = itemgetter( 
    'f7', 'f1', 'f4', 'f9', 'f2', 'f8', 'f10', 'f11', 'f12', 'f17',  
    'f18', 'f19', 'f14', 'f15', 'f16', 'f17', 'f20') 

make_key() 函数可以利用您可以从对象中提取属性的事实; {0.f1} 会将第一个位置参数的 f1 属性插入到 str.format() 方法中;利用它来创建一个只接受一个位置参数的绑定(bind) str.format() 方法:

make_key = '{0.f1}/{0.f2}/{0.f3}'.format