通过询问输入是否是列表,将字典附加到字典中的列表

问题描述

我正在处理字典中的字典列表。

authors=['a','b']

new_item={'itemType': 'journalArticle','title': '','creators': [{'creatorType': 'author','firstName': '','lastName': ''}]}


if type(authors) == 'list':
    new_item['creators'] = []
    for name in authors:
        new_item['creators'].append(dict({'creatorType': 'author','name': name}))
else:
    new_item['creators'] = [{'creatorType': 'author','name': authors}]

new_item

为什么上面的代码给出这个:

{'itemType': 'journalArticle','name': ['a','b']}]}

而不是这个:

{'itemType': 'journalArticle','name': 'a'},{'creatorType': 'author','name': 'b'}]}

解决方法

试试这个简单的方法,

authors=['a','b']
new_item={'itemType': 'journalArticle','title': '','creators': [{'creatorType': 'author','firstName': '','lastName': ''}]}

if isinstance(authors,list):
    new_item['creators'] = [{'creatorType': 'author','name': name} for name in authors]
else:
    new_item['creators'] = [{'creatorType': 'author','name': authors}]

print(new_item)

输出:

{'itemType': 'journalArticle','name': 'a'},{'creatorType': 'author','name': 'b'}]}