循环遍历字典数组并更改一个键值

时间:2018-04-12 00:42:11

标签: python python-3.x python-2.7

例如

sample = [
  {'one':'test', 'two': 'hello'}, 
  {'one':'test', 'two': 'world'}, 
  {'one': 'test', 'two': 'python'}
]

我想改变每个'一个'来自' test'完成'

2 个答案:

答案 0 :(得分:1)

使用for循环并重新分配键的值:

for i in sample:
    i['one'] = 'done'
sample
>>>[{'one': 'done', 'two': 'hello'}, {'one': 'done', 'two': 'world'}, {'one': 'done', 'two': 'python'}]

如果列表中的某些词条可能没有“一个”键,则将重新分配到try块中:

for i in sample:
    try:
        i['one'] = 'done'
    except KeyError:
        pass

答案 1 :(得分:0)

在Python3中,您可以使用字典解包:

sample = [{'one': 'test', 'two': 'hello'}, {'one': 'test', 'two': 'world'}, {'one': 'test', 'two': 'python'}]
new_sample = [{**i, **{'one':'done'}} for i in sample]

输出:

[{'one': 'done', 'two': 'hello'}, {'one': 'done', 'two': 'world'}, {'one': 'done', 'two': 'python'}]

对于Python2,使用列表推导来创建新词典:

new_sample = [{a:'done' if a == 'one' else b for a, b in i.items()} for i in sample]

输出:

[{'one': 'done', 'two': 'hello'}, {'one': 'done', 'two': 'world'}, {'one': 'done', 'two': 'python'}]
相关问题