首页 > 解决方案 > 用列表中的项目定义字典键的 Pythonic 方法

问题描述

有没有一种 Python 的方式来使用列表中的项目来定义字典的键和值?

例如,我可以这样做:

s = {}
a = ['aa', 'bb', 'cc']

for a in aa:
   s['text_%s' %a] = 'stuff %s' %a

In [27]: s
Out[27]: {'text_aa': 'stuff aa', 'text_bb': 'stuff bb', 'text_cc': 'stuff cc'}

我想知道是否可以使用列表理解或其他技巧来迭代列表。

就像是:

s[('text_' + a)] = ('stuff_' + a) for a in aa

谢谢!

标签: python

解决方案


使用字典理解:

{'text_%s' %x: 'stuff %s' %x for x in a}

在较新的版本中:

{f'text_{x}': f'stuff {x}' for x in a}

推荐阅读