如何根据条件更新多个字典值?

时间:2018-02-15 15:58:44

标签: python dictionary

我有一个字典,看起来像:

dict = {'A':[1,2], 'B':[0], 'c':[4]}

需要它看起来像:

dict = {'A':[1,2], 'B':[0,0], 'c':[4,0]}

我现在在做什么:

dict = {x: y+[0] for (x,y) in dict.items() if len(y) < 2}

生成:

dict = {'B':[0,0], 'c':[4,0]}

任何想法如何避免消除那些不符合条件的人?

6 个答案:

答案 0 :(得分:3)

你快到了。尝试:

list3 = list1.copy()

j = 0
for i in range(len(list2)):
    list3[j:j+len(list2[i])] = [list3[j:j+len(list2[i])]]
    j += 1

(如jp_data_analysis所述,避免在my_dict = {x: y + [0] if len(y) < 2 else y for (x,y) in dict.items()} 等内置函数后命名变量

答案 1 :(得分:2)

这是一种方式。

注意:不要在课后命名变量,例如使用d代替dict

d = {'A':[1,2], 'B':[0], 'c':[4]}

d = {k: v if len(v)==2 else v+[0] for k, v in d.items()}

# {'A': [1, 2], 'B': [0, 0], 'c': [4, 0]}

答案 2 :(得分:2)

您可以使用词典理解:

d = {'A':[1,2], 'B':[0], 'c':[4]}
new_d = {a:b+[0] if len(b) == 1 else b for a, b in d.items()}

此外,最好不要将变量分配给影响公共内置函数的名称,例如dict,因为您将覆盖当前名称空间中的函数。

答案 3 :(得分:2)

  1. 您的代码几乎是正确的。您的问题是,您要过滤掉大于2的任何列表。您需要做的只是将它们放在新字典中。这可以使用ternary operator完成。它的格式为value1 if condition else value2

  2. 此外,如果您想要更通用的方法来填充字典中的每个列表 如果长度相等,您可以使用mapmax

  3. 以下是具有上述修改的代码:

    >>> d = {'A':[1, 2], 'B': [0], 'c': [4]}
    >>> 
    >>> max_len = max(map(len, d.values()))
    >>> {k: v + [0] * (max_len - len(v)) if len(v) < max_len else v for k, v in d.items()}
    {'A': [1, 2], 'B': [0, 0], 'c': [4, 0]}
    >>> 
    

答案 4 :(得分:1)

一种普遍的方式:

d = {'A':[1,2], 'B':[0], 'c':[4]}

m = max(len(v) for v in d.values())
for k, v in d.items():
    if len(v) < m:
        d[k].extend([0 for i in range(m-len(v))])

答案 5 :(得分:0)

你非常接近,只需使用update()

dict

就像其他人所说的那样,不要重新分配保留名称,例如componentWillMount() { return ( <div className={this.props.classes.modalLoading}> TESTE </div> ) } ,这是一个单向的街道调试地狱。