为lis中的每个值添加键的快速方法

2024-09-27 19:28:22 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个元素列表

tagsList = ['dun', 'dai', 'che']

如何将上述内容转换为以下内容?你知道吗

tagsDictionaries = [
  {
    'name': 'dun'
  },
  {
    'name': 'dai'
  },
  {
    'name': 'che'
  }
]

我想用for循环来实现这一点


Tags: name元素内容列表forchedaidun
3条回答

下面是一个基本的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]

相关问题 更多 >

    热门问题