Belphegor
Belphegor

Reputation: 4766

Python KeyError exception for initializing dictionary

I have the following code:

for serv in allservices:
    services[serv['id']] = serv
    hosts[serv['host']]['services'][serv['id']] = serv

where allservices is a list of dictionaries and services is a dictionary. This code is in a function, which is called twice. The first time it works fine. On the second time, however, I get this:

File "/media/sf_virtual_shared_folder/workfolder/omeganoc-sprint/onoc/omeganoc/grapher.py", line 338, in get_logical_dependencies_components for serv in allservices: KeyError: 9

Now, I know that the key error is got when we try to enter an element of the dictionary which doesn't exist. But, here I try to initialize or edit some values of the dictionary, and the first time it works fine, and the second it doesn't.

What can be causing this problem and how do I deal with it?

EDIT: The definition of allservices and services:

allservices = [{'id':s.id, 
                'name':s.get_name(),
                'host': s.host.id,
                'required_services': {},
                'dependent_services': {}} 
                for s in shinken.get_all_service()]
...
services = {}

EDIT 2:

OK, with the debugger, I found out that the error is in fact in the last line of the loop, in:

hosts[serv['host']]['services'][serv['id']] = serv

And, it is because in hosts I don't have the element hosts[serv['host']], which is in fact hosts[9], and hence the key error: 9.

However, even if I don't have this element - it should be initialized here, so I still don't get it why it doesn't work?

Upvotes: 2

Views: 2328

Answers (1)

RedBaron
RedBaron

Reputation: 4755

hosts[serv['host']]['services'][serv['id']] = serv

This line does not initialize hosts[serv['host']]. What it does is roughly the following

a=hosts[serv['host']]
b=a['services']
c=b[serv['id']]
c=serv

So rather than initialize hosts[serv['host']], it fetches hosts[serv['host']]. You can get around this problem by using a try except or a get()

Upvotes: 3

Related Questions