我有词典
{
"count_casinos": 4,
"casinos": {
"16": {
"fields": [
{"casino_logo": "assets/images/crown.png"},
{"raiting_casino": "9"},
{"bonus_code": "AX7772"},
{"bonus_summa": "200"},
{"bonus_min_depozit": "1000000"},
{"bonus_veizdjer": "4"}],
"title": "Royal casino casino1"},
"17": {
"fields": [
{"casino_logo": "assets/images/crown.png"},
{"raiting_casino": "8.2"},
{"bonus_code": "AX777"},
{"bonus_summa": "200"},
{"bonus_min_depozit": "1000000"},
{"bonus_veizdjer": "4"}],
"title": "Royal casino casino3"},
"18": {
"fields": [
{"casino_logo": "assets/images/crown.png"},
{"raiting_casino": "9.3"},
{"bonus_code": "AX7772"},
{"bonus_summa": "200"},
{"bonus_min_depozit": "1000000"},
{"bonus_veizdjer": "4"}],
"title": "Royal casino casino2"},
"15": {
"fields": [
{"casino_logo": "assets/images/crown.png"},
{"raiting_casino": "9.9"},
{"bonus_code": "AX777"},
{"bonus_summa": "200"},
{"bonus_min_depozit": "1000000"},
{"bonus_veizdjer": "4"}],
"title": "Royal casino casino4"}}}
当我尝试循环时
for k,v in casino.iteritems():
for iterm in v['fields']:
print iterm['bonus_code']
key:error
出了什么问题?
答案 0 :(得分:1)
如果您遍历v['fields']
,则每个项目只有dict
只有一个密钥的对象,而且只有一个项目有'bonus_code'
个密钥。
轻微的改变不会给你带来错误
for k,v in casino.iteritems():
for iterm in v['fields']:
if 'bonus_code' in iterm: print iterm['bonus_code']
注意:如果casino
是initial_data dict .get('casinos')
<强>更新强>
我猜测OP的casino
变量是
data = {"count_casinos": 4, "casinos": {"16": {"fields": [{"casino_logo": "assets/images/crown.png"}, {"raiting_casino": "9"}, {"bonus_code": "AX7772"}, {"bonus_summa": "200"}, {"bonus_min_depozit": "1000000"}, {"bonus_veizdjer": "4"}], "title": "Royal casino casino1"}, "17": {"fields": [{"casino_logo": "assets/images/crown.png"}, {"raiting_casino": "8.2"}, {"bonus_code": "AX777"}, {"bonus_summa": "200"}, {"bonus_min_depozit": "1000000"}, {"bonus_veizdjer": "4"}], "title": "Royal casino casino3"}, "18": {"fields": [{"casino_logo": "assets/images/crown.png"}, {"raiting_casino": "9.3"}, {"bonus_code": "AX7772"}, {"bonus_summa": "200"}, {"bonus_min_depozit": "1000000"}, {"bonus_veizdjer": "4"}], "title": "Royal casino casino2"}, "15": {"fields": [{"casino_logo": "assets/images/crown.png"}, {"raiting_casino": "9.9"}, {"bonus_code": "AX777"}, {"bonus_summa": "200"}, {"bonus_min_depozit": "1000000"}, {"bonus_veizdjer": "4"}], "title": "Royal casino casino4"}}}
casino = data.get('casinos')
因为如果casino
是OP提出的初始dict
,那么OP会收到另一个错误(TypeError
),因为data['count_casinos']
的值为int
并且int
没有__getitem__
方法
这会引发TypeError
。
答案 1 :(得分:0)
你没有深入到嵌套词典中。如果您只对casinos
部分数据感兴趣,那么这样的内容对您有用。
for k,v in casino['casinos'].iteritems():
data_list = v.get('fields')
# If you know the list index is consistent
print data_list[2].get('bonus_code')
#otherwise
for item in data_list:
if 'bonus_code' in item.keys():
print item['bonus_code']