python - 用列表中的项目定义字典键的 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
谢谢!
解决方案
使用字典理解:
{'text_%s' %x: 'stuff %s' %x for x in a}
在较新的版本中:
{f'text_{x}': f'stuff {x}' for x in a}
推荐阅读
- javascript - 带有 Vuejs 的 Laravel 在没有 php artisan serve 的情况下运行项目
- asp.net-core - 如何在同一个 .net core 3 应用程序中使用剃须刀页面和控制器?
- python - 在 Pandas DataFrame 中查找数值最接近的行
- javascript - 如何在 Metro 中获取 React Native 变体?
- akka - Akka - 在创建时强制道具序列化
- python - Pandas Dataframe 作为 Pyomo 优化模型中的参数
- linkedin - 是否可以使用linkedin API 获取带有特定主题标签的帖子?
- sharepoint-2013 - 有没有办法控制共享点列表项上最后修改的人是谁
- java - 使用单声道
在 Spring 中填充 Cloud Firestore 实体 - javascript - 如何使用 Ajv 编译 JSON Schema 的子集?