我的字典看起来像这样:
reply = {icon:[{name:whatever,url:logo1.png},{name:whatever,url:logo2.png}]}
我如何访问logo1.png?
我试过了:
print reply[icon][url]
它给了我一个错误:
list indices must be integers, not str
EDIT:
请记住,有时候我的字典会改为:
reply = {icon:{name:whatever,url:logo1.png}}
我需要一个适用于两种词典的通用解决方案
EDIT2: 我的解决方案是这样的:
try:
icon = reply['icon']['url']
print icon
except Exception:
icon = reply['icon'][0]['url']
print ipshit,icon
这有效,但看起来很可怕。我想知道是否有比这更简单的方法
答案 0 :(得分:2)
你试过这个吗?
reply[icon][0][url]
如果您确定知道所有不同类型的回复,那么您必须编写一个解析器,以便您明确检查这些值是列表还是单词。
如果只是你所描述的两种可能性,你可以试试这个:
def get_icon_url(reply):
return reply['icon'][0]['url']\
if type(reply['icon']) is list else reply['icon']['url']
答案 1 :(得分:2)
所以在这种情况下,icon是列表的键,它有两个字典,每个字典有两个键/值对。此外,看起来您可能希望自己的密钥成为字符串(icon =' icon',name =' name')..但也许它们是变量,在这种情况下无视,i& #39;我将使用下面的字符串,因为它似乎是最正确的
这样:
reply['icon'] # is equal to a list: []
reply['icon'][0] # is equal to a dictionary: {}
reply['icon'][0]['name'] # is equal to 'whatever'
reply['icon'][0]['url'] # is equal to 'logo1.png'
reply['icon'][1] # is equal to the second dictionary: {}
reply['icon'][1]['name'] # is equal to 'whatever'
reply['icon'][1]['url'] # is equal to 'logo2.png'
你可以通过知道列表中有多少项,以及如上所述明确引用主题来访问这些内部词典的元素,或者你可以迭代它们:
for picture_dict in reply['icon']:
name = picture_dict['name'] # is equal to 'whatever' on both iterations
url = picture_dict['url'] #is 'logo1.png' on first iteration, 'logo2.png' on second.
干杯!
答案 2 :(得分:0)
没有那么不同,但可能看起来更好(KeyError提供更好的控制):
icon_data = reply['icon']
try:
icon = icon_data['url']
print icon
except KeyError:
icon = icon_data[0]['url']
print ipshit,icon
或:
icon_data = reply['icon']
if isinstance(icon_data, list):
icon_data = icon_data[0]
icon = icon_data['url']