首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从文件中读取并存储到包含字典和列表的字典中

从文件中读取并存储到包含字典和列表的字典中
EN

Stack Overflow用户
提问于 2014-11-18 10:14:46
回答 1查看 111关注 0票数 0

我已经在网上搜索了我的问题的答案,我使用了我所学到的一些方面来帮助我达到这一点。然而,我一直无法找到解决方案来达到我需要的位置。

在可能的最短方式中,我需要创建一个字典,其中包含一个字典和从文件中读入的值列表,并打印输出。

我可以使用静态创建的字典来做到这一点,但我似乎无法在从文件读取时以相同的格式创建字典。

以下是我能够运行的代码:

代码语言:javascript
复制
routers = {'fre-agg1': {'interface Te0/1/0/0': ["rate-limit input 135", "rate-limit input 136"],
                        'interface Te0/2/0/0': ["rate-limit input 135", "rate-limit input 136"]},
           'fre-agg2': {'interface Te0/3/0/0': ["rate-limit input 135", "rate-limit input 136", "rate-limit input 137"]}}

for rname in routers:
    print rname
    for iname in routers[rname]:
        print iname
        for int_config in routers[rname][iname]:
            print int_config

这个输出完全按照我需要的格式打印出来:

代码语言:javascript
复制
fre-agg2
interface Te0/3/0/0
rate-limit input 135
rate-limit input 136
rate-limit input 137
fre-agg1
interface Te0/1/0/0
rate-limit input 135
rate-limit input 136
interface Te0/2/0/0
rate-limit input 135
rate-limit input 136

我尝试读入的文件格式不同:

代码语言:javascript
复制
ama-coe:interface Loopback0
ama-coe: ip address 10.1.1.1 255.255.255.255
ama-coe:interface GigabitEthernet0/0/0
ama-coe: description EGM to xyz Gi2/0/1
ama-coe: ip address 10.2.1.1 255.255.255.254
ama-coe:interface GigabitEthernet0/0/1
ama-coe: description EGM to abc Gi0/0/1
ama-coe: ip address 10.3.1.1 255.255.255.254

对于此文件,我希望该文件的输出与上面显示的输出相同,并在接口名下列出接口配置,在设备名下列出接口配置

代码语言:javascript
复制
ama-coe
interface Loopback0
ip address 10.1.1.1 255.255.255.255
interface GigabitEthernet0/0/0
etc etc etc

到目前为止,以下是我拥有的代码:

代码语言:javascript
复制
routers = {}

with open('cpe-interfaces-ipaddress.txt') as inputFile:
    inputData = inputFile.read().splitlines()
    for rname in inputData:
        device, stuff = rname.split(':')
        if not device in routers:
            routers[device] = None
        elif stuff == "interface":
            routers[device][None] = stuff

我知道这段代码非常不完整,但我无论如何也不能像静态创建字典时那样弄清楚字典和列表结构。

如果能提供任何帮助,我们将不胜感激。

谢谢。

EN

回答 1

Stack Overflow用户

发布于 2014-11-18 10:39:23

代码语言:javascript
复制
routers = {}

with open('cpe-interfaces-ipaddress.txt') as inputFile:
    cur_interface = None
    for rname in inputFile:
        device, stuff = rname.strip().split(':')
        print device, stuff, cur_interface
        if not device in routers:
            routers[device] = {}

        if stuff.startswith("interface"):
            key_word, interface = stuff.split(' ')
            routers[device].setdefault(interface, [])
            cur_interface = interface
        else: # ip address
            routers[device][cur_interface].append(stuff)

不知道这是否能满足你的需求。我假设每个ip地址都属于以前的接口。

使用字典来组织东西的方法很常见。你应该学习一些内置的方法,比如setdefaultappend

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26985444

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档