在字典值的条件之后重新排序或重新创建字典键

2024-04-27 19:37:35 发布

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

我有下面的字典

test_dict = {1: 'Okay', 2: 'not good', 3: 'not well', 4: 'fine'}

由此,我想检查一个值的长度是否大于4,如果大于4,则将其分割为大小相等的块。一旦出现块,我想添加一个键并对这些块进行赋值。例如,输出如下所示:

out_dict = {1:'Okay', 2: 'not ', 3: 'good', 4: 'not ', 5: 'well', 6: 'fine'}

如果您看到test_dict的键2和3的字符串大于4,那么它们将被拆分,并且每个拆分都将获得自己的键和拆分值,作为键2、3、4、5的值

这就是我到目前为止所尝试的

list_of_no_change = []
list_of_changed_dicts = []

for k, v in test_dict.items():    
    no_change = {}
    temp_dict = {}
    
    if len(v) > 4:
        # Divide into chunks
        chunks = [v[i:i + 4] for i in range(0, len(v), 4)]
        
        k_increment = 1
        
        for ix, vl in enumerate(chunks):
            
            if ix == 0:
                temp_dict[k] = vl
                
            else:
                new_k = k + k_increment
#                 print('Senetence id::>>>',ix, 'Value::>>>',vl, 'new key value::>>>',new_k)
                temp_dict[new_k] = vl
                k_increment +=1
        
    else:
        no_change[k] = v
        
    list_of_changed_dicts.append(temp_dict)
    list_of_no_change.append(no_change)

我从两个列表中获得的输出,与我的标题不接近:(

list_of_no_change - [{1: 'Okay'}, {}, {}, {4: 'fine'}]
list_of_changed_dicts - [{}, {2: 'not ', 3: 'good'}, {3: 'not ', 4: 'well'}, {}]

任何帮助/建议都会很好


2条回答
    test_dict = {1: 'Okay', 2: 'not good', 3: 'not well', 4: 'fine', 5: 'not good'}
    new_dict = {}
    no_of_chunks = 0
    values_greater_size = 0
    for key, val in test_dict.items():
        if len(val) > 4:
            chunks = [val[i:i + 4] for i in range(0, len(val), 4)]
            for new_val in chunks:
                new_dict.update({key + no_of_chunks - values_greater_size: new_val})
                no_of_chunks = no_of_chunks + 1
            values_greater_size = values_greater_size + 1
        else:
            new_dict.update({key + no_of_chunks - values_greater_size: val})
    print(new_dict)

我不确定这两张表的目的是什么,但主要问题是你根本数错了。解决此问题的最简单方法是无条件分块,然后使用enumerate()构造输出

chunks = (v[i:i+4] for v in test_dict.values() for i in range(0, len(v), 4))
out_dict = {i: s for i, s in enumerate(chunks, 1)}
# {1: 'Okay', 2: 'not ', 3: 'good', 4: 'not ', 5: 'well', 6: 'fine'}

在这里,我使用了chunks一个生成器表达式来避免构建列表

我假设您使用的是Python3.7+,其中dicts保留插入顺序。如果没有,您可以用(test_dict[k] for k in sorted(test_dict))替换test_dict.values()

相关问题 更多 >