代码之家  ›  专栏  ›  技术社区  ›  ahajib Shaun McHugh

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

  •  1
  • ahajib Shaun McHugh  · 技术社区  · 7 年前

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

    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 回复  |  直到 7 年前
        1
  •  3
  •   Phydeaux    7 年前

    你就快到了。尝试:

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

    (正如jp\u data\u analysis所提到的,避免将变量命名为内置变量,如 dict )

        2
  •  2
  •   jpp    7 年前

    这是一种方式。

    笔记 :不要在类后命名变量,例如使用 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]}
    
        3
  •  2
  •   Ajax1234    7 年前

    您可以使用字典理解:

    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 ,因为您将重写当前命名空间中的函数。

        4
  •  2
  •   Chris    7 年前
    1. 您的代码几乎正确。您的问题是,您正在筛选出任何大于 2 . 相反,您需要做的只是将它们原封不动地放在新词典中。可以使用 ternary operator . 它有这样的形式 value1 if condition else value2 .

    2. 此外,如果您想用一种更通用的方法将字典中的每个列表填充到 长度相等,可以使用 map max .

    以下是经过上述修改的代码:

    >>> 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]}
    >>> 
    
        5
  •  1
  •   ZaxR    7 年前

    通用方式:

    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))])
    
        6
  •  0
  •   r.ook jpp    7 年前

    你离得很近,用吧 update() :

    d = {'A':[1,2], 'B':[0], 'c':[4]}
    
    d.update({x: y+[0] for (x,y) in d.items() if len(y) < 2})
    
    d
    # {'A': [1, 2], 'B': [0, 0], 'c': [4, 0]}
    

    正如其他人所说,不要使用像这样的重新分配保留名称 dict ,这是通往调试地狱的单行道。