创建三层字典并从第三层打印

2024-05-17 10:18:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个三层字典来存储MPLS电路信息。我只尝试了2层,但发现信息被字典层的最后一个条目覆盖了。你知道吗

一旦我有了那本词典,我希望能够通过打印语句向用户呈现该词典中可用的载体。你知道吗

这是我的字典结构。你知道吗

carriers = {
    '4': {
        'AT&T': {
            "Role":"Primary", "Interface":"TenGigabitEthernet4/3/0", "Location":"Computer Center"},
        'CentPri': {
            "Role":"Primary", "Interface":"GigabitEthernet4/0/0", "Location":"Computer Center"},
        'CentSec': {
            "Role":"Secondary", "Interface":"GigabitEthernet1/2/0", "Location":"ESF"},
        'Verizon': {
            "Role":"Primary", "Interface":"GigabitEthernet1/0/0", "Location":"ESF"}
        },
    '2': {
        "TeliaSonera": {
            "Role":"Primary", "Interface":"GigabitEthernet0/0/1", "Location":"Mannheim"},
        "Verizon": {
            "Role":"Primary", "Interface":"GigabitEthernet0/0/0.40", "Location":"Mannheim"},
        "AT&T": {
            "Role":"Primary", "Interface":"GigabitEthernet1/0/0.2", "Location":"Mannheim"}
        },
    '1': {
        'Tata': {
            "Role":"Primary", "Interface":"GigabitEthernet0/0/6", "Location":"TCI - 1, Pune, India"}
        }
            }

在这里,我询问用户选择哪个地区,然后询问他们想知道哪个运营商。你知道吗

region_choice = raw_input("Select a Region: (1-4)\n")
if region_choice in carriers:
    carrier_choice = raw_input("Select from the following carriers: {}".format(carriers[region_choice][0]))

我意识到在运营商[地区选择]之后我有一个[0],但这就是我被困的地方。你知道吗

如何显示所选词典中的所有载体?你知道吗

期望结果:

选择区域:(1-4) 4个

从以下运营商中选择:AT&T、CentPri、CentSec、Verizon 美国电话电报公司

剩下的我可以在这里做。你知道吗


Tags: 用户信息字典locationregioninterfacerole运营商
1条回答
网友
1楼 · 发布于 2024-05-17 10:18:42
region_choice = raw_input("Select a Region: (1-4)\n")
if region_choice in carriers:
    carrier_choice = raw_input("Select from the following carriers: {}".format(", ".join(carriers[region_choice].keys())))

结果:

Select a Region: (1-4)
4
Select from the following carriers: CentSec, AT&T, Verizon, CentPri

基本上你想要你所在地区的keys。这将返回一个list,您可以通过join将其转换为字符串。你知道吗

请记住,由于dict是无序的,因此不能保证字符串中的载波顺序。为此你需要一个^{}。你知道吗

相关问题 更多 >