简体   繁体   中英

Create Dictionary of Dictionary at Run time in python from a data from a file

How can we create the Below dictionary of dictionary in python at runtime.

Attached code snippet with desired output when data is manually stored in dictionary.

When Input would be taken from InputFile???

Input File

00

Called 999000

VLR 365444564544

Calling 2756565

16

reason_code 12

level 4

severity minor

Script :

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

How can we create the above dictionary of dictionary in python at runtime When Input would be taken from InputFile???

Looks like the lines with just keys can be detected by counting the words in them, and then the key may be used until there is a new key. Here's an example implementation:

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

Test it:

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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM