Help with nested dictionary - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Help with nested dictionary (/thread-13036.html) |
Help with nested dictionary - Anidil - Sep-24-2018 myStr = '''Ethernet Channel Bonding Driver: v3.7.1 (April 27, 2011) I have the above text outputs and I want to create a nested dictionary as follows:bond0 : { 'MII Status:' : 'up', 'Aggregator ID:' : '2', 'Slave Interfaces' : { 'p1p1' : { 'MII Status' : 'up', 'Permanent HW addr' : '9c:dc:71:45:eb:80', 'MII Status' : up }, 'p4p1' : { ''MII Status' : 'up', 'Permanent HW addr' : '9c:dc:71:4d:80:20', 'MII Status' : up }, }, I began doing some coding as shown below, but still not getting there : from __future__ import print_function class BndClass(dict): def __init__(self, Bnd=None): self['Name'] = Bnd self.uPdateInfo() super(BndClass, self).__init__() def uPdateInfo(self): for line in myStr.splitlines(): match = re.search(r'^Cur.*?:\s+(.*?)$', line) if match: self['act_int'] = match.group(1) match = re.search(r'^\s*?Aggregator ID:\s+(\d)$', line) if match: self['agid'] = match.group(1) match = re.search(r'^Slave\sInterface:\s(.*?)$', line) if match: self.setdefault('slvs', []).append(match.group(1)) if __name__ == '__main__': Y = BndClass('bond0') Y {'Name': 'bond0', 'agid': '2', 'slvs': ['p1p1', 'p4p1']}please help RE: Help with nested dictionary - Larz60+ - Sep-24-2018 I added code tags for you. It's so much easier to read a dictionary if written like: bond0: { 'MII Status:': 'up', 'Aggregator ID:': '2', 'Slave Interfaces': { 'p1p1': { 'MII Status': 'up', 'Permanent HW addr': '9c:dc:71:45:eb:80', 'MII Status': up }, 'p4p1': { 'MII Status' : 'up', 'Permanent HW addr': '9c:dc:71:4d:80:20', 'MII Status': up } } }you can use something like the following to traverse a nested dictionary: def display_dict(thedict): for key, value in thedict.items(): if isinstance(value, dict): print(f'{key}:') self.display_dict(value) else: print(f' {key}: {value}') display_dict(bond0)This also corrects errors you had in your definition |