Search code examples
pythonlistisinstance

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


I am working with a list of dictionaries within a dictionary.

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

Why does the above code give this:

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

instead of this:

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

Solution

  • Try this simple way,

    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)
    

    Output:

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