简体   繁体   English

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

[英]Re-order or Recreate Dictionary keys after a conditions for dictionary values -

I have the following dictionary,我有以下字典,

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

From this, I want to check if a value's length is greater than 4 and if it is, then split into evenly sized chunks.由此,我想检查一个值的长度是否大于 4,如果是,则分成大小均匀的块。 As soon as the chunks happen, I want to add a key and value those chunks.一旦块发生,我想添加一个键并为这些块赋值。 For example, output like this:例如,output 像这样:

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

If you see since test_dict 's key 2 and 3 had strings greater than 4, they get split and each split should get its own key and split value as values for keys 2,3,4,5.如果您看到由于test_dict的键 2 和 3 的字符串大于 4,它们会被拆分,并且每个拆分都应该获得自己的键和拆分值作为键 2、3、4、5 的值。

This is what I have tried so far,这是我到目前为止所尝试的,

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)

The output I get from both lists, which not close to where I am heading:(我从两个列表中得到的 output 离我要去的地方不近:(

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

Any help/suggestions to achieve my output would be great.任何帮助/建议来实现我的 output 都会很棒。

I'm not sure what you're going for with the two lists, but the main problem is that you're simply not counting correctly.我不确定您要使用这两个列表做什么,但主要问题是您根本没有正确计算。 The easiest way to fix this is by chunking unconditionally, then using enumerate() to construct the output.解决此问题的最简单方法是无条件分块,然后使用enumerate()构造 output。

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

Here I made chunks a generator expression to avoid constructing a list.在这里,我将chunks设置为生成器表达式以避免构造列表。

I'm assuming you're using Python 3.7+, where dicts preserve insertion order.我假设您使用的是 Python 3.7+,其中 dicts 保留插入顺序。 If not, you could replace test_dict.values() with (test_dict[k] for k in sorted(test_dict)) .如果没有,您可以将test_dict.values()替换为(test_dict[k] for k in sorted(test_dict))

    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)

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

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