-1

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'}]}
Sati
  • 716
  • 6
  • 27

1 Answers1

1

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'}]}
Nanthakumar J J
  • 860
  • 1
  • 7
  • 22
  • 2
    You could replace ``type(authors) is list`` with ``isinstance(authors, list)`` which would be more appropriate. – sushanth May 24 '21 at 05:33
  • What's the difference between the 2 expressions? `type(authors) == 'list'` also returns `True` when `authors` variable is a list. – Sati May 24 '21 at 06:03
  • 1
    type command returns only strings, so the proper way to check is either by using isinstance or membership operator – Nanthakumar J J May 24 '21 at 06:04