Создать словарь словаря во время выполнения в Python из данных из файла - PullRequest
0 голосов
/ 05 декабря 2018

Как мы можем создать словарь «Ниже» словаря в python во время выполнения.

Прикрепленный фрагмент кода с желаемым выводом, когда данные вручную сохраняются в словаре.

Когда ввод будет взят из InputFile???

Входной файл

00

Вызывается 999000

VLR 365444564544

Вызов2756565

16

код причины 12

уровень 4

незначительный уровень

Сценарий:

Operation = {'00': {'Called': '999000', 'calling': '2756565', 'vlr': '365444564544'},
                    '16': {'reason_code': '12'}
                   }

for op_id, op_info in Operation.items():
    print("\n Operation ID:", op_id)

    for key in op_info:
        print(key + ':', op_info[key])

OUTPUT

Operation ID: 00

        Called: 999000

        vlr: 365444564544

        calling: 2756565

 Operation ID: 16

             reason_code: 12 

             level :4

             severity :minor

Как мы можем создать вышеупомянутый словарь словаря в python во время выполнения, когда Input будет взят из InputFile ???

1 Ответ

0 голосов
/ 05 декабря 2018

Похоже, что строки с просто ключами можно обнаружить, посчитав слова в них, и затем ключ можно использовать до тех пор, пока не появится новый ключ.Вот пример реализации:

def file2dict(file_name):
  with open(file_name) as f:
    res = dict()                 # result
    key = ""                     # we keep the key until there is a new one
    for line in f.readlines():
      words = line.split()       # get words in lines
      if (words):                # check if the line was not empty
        if (len(words) == 1):    # if the length is one, we know this is a new key 
          key = words[0]         # and we change the key in use
          res[key] = dict()      # and create a dict element 
        else:
          res[key][words[0]] = words[1]  # and add key-value pairs in each line
return res

Проверьте это:

print(file2dict("in.txt")) # your example file

Вывод:

{'00': {'Called': '999000', 'VLR': '365444564544', 'Calling': '2756565'}, '16': {'reason_code': '12', 'level': '4', 'severity': 'minor'}}
...