代码之家  ›  专栏  ›  技术社区  ›  Gambit1614

用列表理解修改词典列表

  •  3
  • Gambit1614  · 技术社区  · 7 年前

    所以我有下列字典

    myList = [{'one':1, 'two':2,'three':3},
              {'one':4, 'two':5,'three':6},
              {'one':7, 'two':8,'three':9}]
    

    这只是我的字典的一个例子。我的问题是,有可能以某种方式修改say key two 在所有的字典里变成他们价值的两倍, 使用列表理解?

    我知道如何使用列表理解来创建新的字典列表,但不知道如何修改它们,我想出了这样的方法

    new_list = { <some if condiftion> for (k,v) in x.iteritems() for x in myList  }
    

    我不知道如何在 <some if condiftion> ,我所想到的嵌套列表理解格式是否正确?

    我想要像这样的例子的最终输出

    [ {'one':1, 'two':4,'three':3},{'one':4, 'two':10,'three':6},{'one':7, 'two':16,'three':9}  ]
    
    5 回复  |  直到 7 年前
        1
  •  4
  •   jezrael    7 年前

    使用列表理解和嵌套的dict理解:

    new_list = [{ k: v * 2 if k == 'two' else v for k,v in x.items()} for x in myList]
    print (new_list)
    [{'one': 1, 'two': 4, 'three': 3}, 
     {'one': 4, 'two': 10, 'three': 6}, 
     {'one': 7, 'two': 16, 'three': 9}]
    
        2
  •  1
  •   lenik    7 年前
    myList = [ {'one':1, 'two':2,'three':3},{'one':4, 'two':5,'three':6},{'one':7, 'two':8,'three':9}  ]
    
    [ { k: 2*i[k] if k == 'two' else i[k] for k in i } for i in myList ]
    
    [{'one': 1, 'three': 3, 'two': 4}, {'one': 4, 'three': 6, 'two': 10}, {'one': 7, 'three': 9, 'two': 16}]
    
        3
  •  1
  •   jpp    7 年前

    简单的 for 循环应该足够了。但是,如果您想使用字典理解,我发现定义映射字典比三元语句更具可读性和可扩展性:

    factor = {'two': 2}
    
    res = [{k: v*factor.get(k, 1) for k, v in d.items()} for d in myList]
    
    print(res)
    
    [{'one': 1, 'two': 4, 'three': 3},
     {'one': 4, 'two': 10, 'three': 6},
     {'one': 7, 'two': 16, 'three': 9}]
    
        4
  •  0
  •   Black Lion    7 年前

    你好你试过这个了吗:

    for d in myList:
      d.update((k, v*2) for k, v in d.iteritems() if k == "two")
    

    谢谢

        5
  •  0
  •   Aran-Fey Kevin    7 年前

    在Python3.5+中,可以在 PEP 448 是的。这将创建每个dict的副本,然后覆盖密钥的值 two 以下内容:

    new_list = [{**d, 'two': d['two']*2} for d in myList]
    # result:
    # [{'one': 1, 'two': 4, 'three': 3},
    #  {'one': 4, 'two': 10, 'three': 6},
    #  {'one': 7, 'two': 16, 'three': 9}]