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

Python 将for循环转换为列表理解以形成字典,python,python-3.x,Python,Python 3.x,有一个字典作为输入,第二个字典是根据它在以下代码中形成的: 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) 打印

有一个字典作为输入,第二个字典是根据它在以下代码中形成的:

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)
打印出来的地方:

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

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

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

# 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'}

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

# 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'}

您可以将for循环重新写入,如下所示:

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)
输出


您可以将for循环重新写入,如下所示:

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)
输出


你可以通过一个单独的听写理解来完成,如下所示:

>>> 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()}

你可以通过一个单独的听写理解来完成,如下所示:

>>> 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()}

如果你要查字典,那就更好了

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

如果你要查字典,那就更好了

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