我正在寻找与字典中的键关联的所有值。有时键包含单个字典,有时是字典列表。
a = {
'shelf':{
'book':{'title':'the catcher in the rye', 'author':'j d salinger'}
}
}
b = {
'shelf':[
{'book':{'title':'kafka on the shore', 'author':'haruki murakami'}},
{'book':{'title':'atomised', 'author':'michel houellebecq'}}
]
}
这是我阅读书架上每本书标题的方法。
def print_books(d):
if(len(d['shelf']) == 1):
print d['shelf']['book']['title']
else:
for book in d['shelf']:
print book['book']['title']
它有效,但看起来不整洁或 pythonic。 for 循环在单值情况下失败,因此 if/else。
你能改进一下吗?
请您参考如下方法:
考虑到如果您有一个包含单个项目的列表(我认为它应该是这样的),您的代码将会中断,如果您真的不能更改您的数据结构,那么这会更加健壮和逻辑:
def print_books(d):
if isinstance(d['shelf'], dict):
print d['shelf']['book']['title']
else:
for book in d['shelf']:
print book['book']['title']
