使用列表推导式修改字典列表

6

我有一个字典列表如下

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

这只是我所拥有的一个字典示例。我的问题是:是否可以使用列表推导式,以某种方式修改字典中所有键为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}  ]

列表推导式用于构建新的列表,而不是修改旧的列表。 - Scott Hunter
3
你所创建的是字典推导式而不是列表推导式。至于 {[ 这些符号。 - roganjosh
5个回答

8
使用嵌套字典推导式进行列表推导:
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}]

3
在Python 3.5+中,您可以在字典字面值中使用新的解包语法,这是在PEP 448中引入的。这将创建每个字典的副本,然后覆盖键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}]

1
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}]

1
一个简单的 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}]

谢谢!我不知道我们可以像这样使用映射! - Gambit1614
2
@MohammedKashif,是的,主要问题是在一个条件下,if/else三元运算符是可以的。但如果你有更多的条件,它会变得(更)难读。 - jpp

0

你好,你试过这个了吗:

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

谢谢


为什么不使用 d['two'] = d['two'] * 2 而不是那个 d.update(...) 呢? - Aran-Fey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接