如何解决通过询问输入是否是列表,将字典附加到字典中的列表
我正在处理字典中的字典列表。
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'}]}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。