如何更新列表字典中的值 [英] how to update values in dictionary of lists

查看:215
本文介绍了如何更新列表字典中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新列表字典
中的值EX:我有字典输入:

I'm trying to update values in dictionary of lists EX: I have a dictionary input:

d={0: [0,1], 1:[1],2:[2],3:[3]}

[0,2]
对,我想将dict中的每个0替换为0.2,并增加每个值> 2比1,因此这里的预期输出是:

and pair [0,2] and I want to replace every 0 in dict with 0,2 and increase each value >2 by 1, so here the expected output:

{0: [0,2,1], 1:[1],2:[2],3:[4]}

我尝试遍历所有值,但这并不能正确地解决问题。

I tried to iterate over all values, but it didn't make the trick properly

def update_dict(_dict,_pair):
    for i in range(len(_dict.keys())):
        for j in range(len(_dict.values()[i])):
            if dict[i][j]==_pair[0]:
                dict[i][j].remove(_pair[0])
                dict[i].append(_pair)
    return _dict

如何实现?
预先感谢您的帮助

How do I achieve that? Thanks in advance for any help

推荐答案

您在这里不需要词典,您需要列表;您有一个从0开始的有序键序列,列表的索引将更有效地满足需要:

You don't need a dictionary here, you want a list; you have an ordered series of keys starting at 0, indices of a list would more efficiently serve that need:

l = [[0,1], [1], [2], [3]]

您可以生成期望的输出:

You can produce the desired output:

for i, nested in enumerate(l):
    # replace all 0 values with 1, 2
    while 0 in nested:
        zero_index = nested.index(0)
        nested[zero_index:zero_index + 1] = [1, 2]
    # increment values in the nested list if the index is over 2:
    if i > 2:
        nested[:] = [v + 1 for v in nested]

此在原位置更改原始嵌套列表。

This alters the original nested lists in-place.

这篇关于如何更新列表字典中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆