python - KeyError when appending to a dictionary of lists -
i want use dictionary record data relating ip addresses, ip address can have number of groups associated it, , need capture info groups relating ip address (these controller groups on wireless system data relating configuration of access points). want like:
{<ip_addr>: [{group_name: my_aps, total_aps: 22, total_active_aps: 12}, {group_name: my-other_aps, total_aps: 15, total_active_aps:14}, {...} ] }
my script looping through list of groups (there 300+) , pulling info off wireless controller. each loop obtain details of new group. can't work out how add group dictionary list. trying (where group_details group dictionary , lms_ip address want list against):
lms_groups[lms_ip].append(group_details)
but get:
keyerror: 'xxx.xxx.xxx.xxx'
(ip address hidden fwiw)
the script seems work point, think dictionaries being created ok.
option 1
dict.setdefault
lms_groups.setdefault(lms_ip, []).append(group_details)
option 2
collections.defaultdict
from collections import defaultdict lms_groups = defaultdict(list) ... lms_groups[lms_ip].append(group_details)
Comments
Post a Comment