Vladleelee Lee Vladleelee Lee - 2 months ago 15
Python Question

strange error in loops

I have dict

{"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"}}}


when I try loop

for k,v in casino.iteritems():
for iterm in v['fields']:
print iterm['bonus_code']


key:error


what's wrong?

Answer

If you iterate through v['fields'] each item will be dict object with only one key, and only one item have 'bonus_code' key.

Slight change that won't get you an error

 for k,v in casino.iteritems():
     for iterm in v['fields']:
         if 'bonus_code' in iterm: print iterm['bonus_code']

NOTE: if casino is initial_data dict .get('casinos')

UPDATE

I made a guess that OP's casino variable is

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')

because if casino would be initial dict that OP presented, then OP will get another error(TypeError), because values of data['count_casinos'] is int and int don't have __getitem__ method which would raise TypeError.