繁体   English   中英

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

[英]Modifying list of dictionary using list comprehension

所以我有以下字典列表

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

这只是我所拥有的字典的一个例子。 我的问题是,有可能以某种方式修改所有字典中的密钥two使用列表理解成为其值的两倍

我知道如何使用list comprehension创建新的字典列表,但不知道如何修改它们,我想出了类似这样的东西

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

使用列表理解与嵌套字典理解:

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

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

你好,你试过这个:

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

谢谢

在python 3.5+中,您可以在PEP 448中引入的dict文字中使用新的解包语法。 这将创建每个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}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM