anonymous
anonymous

Reputation: 143

Read a text file and convert into nested dict of dict with same keys using python

I want python to read text file and create a nested dict. I have these datas in a text file abc.

'name':'a', 'age':11, 'blood group':'A+ve', 'mob num':123456, 'address':'12,abc street'

'name':'b', 'age':12, 'blood group':'A-ve', 'mob num':124, 'address':'112,abc street'

I have read the text file but I dont know how to proceed. I'm a beginner in python.

with open ("text.txt",'r') as f:
    for line in f:
        print line

My output should look like

{Name:a,b Age:11,12 { blood group: A+ve,A -ve {Mob num: 123456,124 {Address: 12 abc street, 112 abc street}}}}

Upvotes: 0

Views: 1560

Answers (2)

TLOwater
TLOwater

Reputation: 638

This code will allow you to write each row to a list as a dictionary:

dicts_from_file = []
with open ("text.txt",'r') as f:
    for row in f:
        row = "{" + row + "}"
        dicts_from_file.append(eval(row))
    print dicts_from_file

Then iterate through each dictionary writing to a master dict:

master_dict = {}
for dict in dicts_from_file:
    for x in dictionary:
        if x in master_dict:
            master_dict[x].append(dictionary[x])
        else:
            master_dict[x] = [dictionary[x]]
print(master_dict)

This doesn't have the issue with the addresses either.

EDIT

Data_Structure = {"Name": [], "Age":[], "Other":{ "blood group": [], More: {"Mob num": [], "Address": []}}}}

Say I want to write to the 3rd nested dictionary (Mob Number) you would say Data_Structure["Other"]["More"]["Mob num"].append('040010909'). The original syntax doesn't make sense because you have to have a key for each sub-dictionary.

Final Edit

Here's a bit of code to show you how the matching of keys might work. It's not super elegant but it works:

some_dict = {"name": [], "age": [],  "other": {"mob num":[],"address":[]}}

with open("hello.txt", 'r') as input_file:
    for row in input_file:
        row = "{" + row + "}"
        this_rows_dict = eval(row)
        for key in this_rows_dict:
            if key == 'name':
                some_dict['name'].append(this_rows_dict[key])
            elif key == 'age':
                some_dict['age'].append(this_rows_dict[key])
            elif key == 'mob num':
                some_dict["other"]["mob num"].append(this_rows_dict[key])
            elif key == "address":
                some_dict["other"]["address"].append(this_rows_dict[key])
            else:
                print("Unknown Key: {}".format(key))
print some_dict

Upvotes: 1

sv_jan5
sv_jan5

Reputation: 1573

I hope this might be sufficient to give you a kick start:

data = dict()
data['name'], data['age'],data['group'],data['num'],data['address'] = [],[],[],[],[] 

with open ("text.txt",'r') as f:
    for line in f:
        key_val_pairs = line.split(',')
        for kv_pair in key_val_pairs:
            k_v = kv_pair.split(':')
            key = k_v[0]
            val = k_v[1]
            data[key].append(val)

Upvotes: 0

Related Questions