2024-09-27 19:28:22 发布
网友
假设我有一个元素列表
tagsList = ['dun', 'dai', 'che']
如何将上述内容转换为以下内容?你知道吗
tagsDictionaries = [ { 'name': 'dun' }, { 'name': 'dai' }, { 'name': 'che' } ]
我想用for循环来实现这一点
for
下面是一个基本的for循环,它将为您提供所需的输出:
tagsList = ['dun', 'dai', 'che'] tagsDictionaries = [] for name in tagsList: new_dict = {'name': name} tagsDictionaries.append(new_dict) print(tagsDictionaries)
以下是您的输出:
[{'name': 'dun'}, {'name': 'dai'}, {'name': 'che'}]
像这样的东西对一本扁平的字典是有用的。每次都需要唯一的键值:
for tag in tagsList: tagDictionary.update({tag + 'uniquekey': tag})
您在示例中展示的是一个字典列表,可以按以下方式完成:
for tag in tagsList: tagListDict.append({'name': tag})
tagsDictionaries = [{'name': item} for item in tagsList]
下面是一个基本的for循环,它将为您提供所需的输出:
以下是您的输出:
像这样的东西对一本扁平的字典是有用的。每次都需要唯一的键值:
您在示例中展示的是一个字典列表,可以按以下方式完成:
相关问题 更多 >
编程相关推荐