Oll*_*ass 1 python dictionary key
我希望获得与字典中的键相关联的所有值.有时密钥包含一个字典,有时候是一个字典列表.
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'}}
]
}
Run Code Online (Sandbox Code Playgroud)
这是我阅读书架上每本书的标题的方法.
def print_books(d):
if(len(d['shelf']) == 1):
print d['shelf']['book']['title']
else:
for book in d['shelf']:
print book['book']['title']
Run Code Online (Sandbox Code Playgroud)
它有效,但看起来不整齐或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']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6892 次 |
| 最近记录: |