通过询问输入是否为列表来追加字典以在字典中列出

Appending dictionaries to list within a dictionary by asking if input is a list

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

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',
 'title': '',
 'creators': [{'creatorType': 'author', 'name': ['a', 'b']}]}

而不是这个:

{'itemType': 'journalArticle',
 'title': '',
 'creators': [{'creatorType': 'author', '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', 'title': '', 'creators': [{'creatorType': 'author', 'name': 'a'}, {'creatorType': 'author', 'name': 'b'}]}