将for循环转换为列表理解以形成字典

时间:2020-10-31 18:47:19

标签: python python-3.x

有一个字典作为输入,下面的代码将基于该字典形成第二个字典:

America/Los_Angeles

它打印出来的地方:

dict1 = {'a': 'ok', 'b': 'ok', 'c': 'needs repair'}

final_dict = {}
for d in dict1.items():
    if d[1] == 'ok':
        final_dict[d[0]] = 'needs repair'
    else:
        final_dict[d[0]] = 'ok'

print(final_dict)

如何将for循环更改为列表理解?

4 个答案:

答案 0 :(得分:1)

您可以使用字典理解-列表理解在这里没有多大意义:

# what to change into what
flipper = {"ok":"needs repair", "needs repair":"ok"}

source = {'a': 'ok', 'b': 'ok', 'c': 'needs repair'}
flipped = { key:flipper[value] for key, value in source.items()}

print(source)
print(flipped)

输出:

{'a': 'ok', 'b': 'ok', 'c': 'needs repair'}
{'a': 'needs repair', 'b': 'needs repair', 'c': 'ok'}

答案 1 :(得分:1)

您可以将for循环重新编写为dictionary comprehension,如下所示:

dict1 = {'a': 'ok', 'b': 'ok', 'c': 'needs repair'}

result = {k: 'needs repair' if v == 'ok' else 'ok' for k, v in dict1.items()}
print(result)

输出

{'a': 'needs repair', 'b': 'needs repair', 'c': 'ok'}

答案 2 :(得分:1)

您可以通过以下单个dict理解来做到这一点:

>>> final_dict = {k: 'needs repair' if v == 'ok' else 'ok' for k, v in dict1.items()}
>>> final_dict
{'a': 'needs repair', 'b': 'needs repair', 'c': 'ok'}
>>> 

在实践中,我会排长队:

final_dict = {k: 'needs repair' if v == 'ok' else 'ok'
              for k, v in dict1.items()}

答案 3 :(得分:0)

如果您要求字典理解,那将是更好的选择

final_dict = { k: 'needs repair' if v=='ok' else 'ok' for k,v in dict1.items()}