如何从字符串创建嵌套字典

时间:2019-06-25 09:26:34

标签: python-3.x

我有一个与程序输出有关的字符串,现在我需要将字符串转换为字典。我已经使用dict()zip()命令进行了尝试,但是无法获取结果。

这是我到目前为止的代码:

string = "Eth1/1 vlan-1 typemode-eth status:access eth1/2 vlan-1 type-eth status:access"
list1=string.split(' ')
 print(list1)
['Eth1/1', 'vlan-1', 'typemode-access']

除此之外,我不知道:

{'eth1/1': {'Speed': '10Gb', 'Vlan': 1, 'Type Mode': 'eth', 'status': 'access'}, 'eth1/2': {'Speed': '10Gb', 'Vlan': 1, 'Type Mode': 'eth', 'status': 'access'}}

2 个答案:

答案 0 :(得分:0)

从结果中获取值,请参见以下示例。查看内嵌评论。

import re

result = {}

string = "Eth1/1 vlan-1 typemode-eth status:access eth1/2 vlan-1 type-eth status:access"

a = re.search('access', string)  # this gives 2 positions for the word access.

list1 = [string[0:a[0]], string[[a[0]+1]:]]   # two substrings. a[0] is used to get 
        # roughly the middle of the string where the spplitpoint is of both
        # substrings. Using access as key word gives flexibility if there is a third
        # substring as well.

result = dict(list1)  # result should be same as result2.

#            y1         z1 
result2 = {'eth1/1': {'Speed': '10Gb', 'Vlan': 1, 'Type Mode': 'eth', 'status': 'access'},
           'eth1/2': {'Speed': '10Gb', 'Vlan': 1, 'Type Mode': 'eth', 'status': 'access'}}
#            y2 = eth1/2.

#             y1        y2
x = result['eth1/1']['Speed']   # replace any word at y1 or z1 to fetch another result.

print ('Got x : %s' % x)   # this prints '10Gb'.

基本上,您创建的是嵌套字典。因此,首先寻址y1可以从特定字典中获取数据。在y1之后,调用z1是从您的第一个嵌套字典中的特定键获取值。如果您在x处更改关键字,则返回的值将有所不同(尽管示例中的关键字看起来相同;请尝试使用不同的值以查看结果)。享受吧!

答案 1 :(得分:0)

在下面尝试此代码:

string = "Eth1/1 vlan-1 typemode-eth status:access eth1/2 vlan-1 type-eth status:access eth1/3 vlan-1 type-eth status:access"

strList = string.split(" ")

indexPos = []

for data in range(0,len(strList)):
   if strList[data].lower()[0:3] == 'eth':
     print('Found',data)
     indexPos.append(data)

dataDict = dict()
for i in range(0,len(indexPos)):
   stringDict = dict()
   stringDict['Speed'] = '10Gb' 
   if i is not len(indexPos)-1:
      string = strList[indexPos[i]:indexPos[i+1]]
   else:
      string = strList[indexPos[i]:]

   for i in range(0,len(string)):
      if i is not 0:
         if i is not 3:
            valueSplit = string[i].split('-')
         else:
            print(i)
            valueSplit = string[i].split(':')

        stringDict[valueSplit[0]] = valueSplit[1] 
   dataDict[string[0]] = stringDict

我已经按照代码中的模式编写了此代码。请让我知道它是否对您有用。