Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a list of dynamic dictionary python

The following is my data set from a text file.

2.1,3.5,1.4,0.2,Iris
4.9,3.0,1.4,0.2,Ilia
3.7,3.2,1.3,0.2,Iridium

There is a list named:

list_of_keys 

which holds the following values in the list

['S_Length','S_Width','P_Length','P_Width','Predicate']

So, the problem is, i want to create a list of dictionary to hold all my data (from the text file) using the list_of_keys as keys for the dictionary as follows:

dict = 
      {'S_Length': 2.1, 'S_Width':3.5 , 'P_Length': 1.4, 'P_Width': 0.2, 'Predicate': Iris},
      {'S_Length': 4.9, 'S_Width':3.0 , 'P_Length': 1.4, 'P_Width': 0.2, 'Predicate': Ilia},
      ... so on!

what i have up to now:

# store all data from the text files as list
all_examples = file.readlines()

for outer_index in range(len(all_examples)):
     for inner_index in range(0, len(list_of_keys)+1):
like image 754
Clint Whaley Avatar asked Feb 12 '16 08:02

Clint Whaley


People also ask

How do you make a nested dictionary dynamically in Python?

To create a nested dictionary, simply pass dictionary key:value pair as keyword arguments to dict() Constructor. You can use dict() function along with the zip() function, to combine separate lists of keys and values obtained dynamically at runtime.


2 Answers

You can use a generator function like following:

def func():
    list_of_keys = ['S_Length','S_Width','P_Length','P_Width','Predicate']
    with open('example.txt') as f:
        for line in f:
            yield dict(zip(list_of_keys,line.strip().split(',')))

print(list(func()))
[{'P_Width': '0.2', 'S_Length': '2.1', 'Predicate': 'Iris', 'S_Width': '3.5', 'P_Length': '1.4'}, {'P_Width': '0.2', 'S_Length': '4.9', 'Predicate': 'Ilia', 'S_Width': '3.0', 'P_Length': '1.4'}, {'P_Width': '0.2', 'S_Length': '3.7', 'Predicate': 'Iridium', 'S_Width': '3.2', 'P_Length': '1.3'}]

you can read the file line by line and split the lines, then create the pairs of keys and values using zip function and then convert them to a dictionary.

Note that since a file object is an iterator you can iterate over your file object and use with statement to open your file which will close the file at the end of the block.

As another alternative and more pythonic way you can also use csv module to read your text file :

import csv
def func():
    list_of_keys = ['S_Length','S_Width','P_Length','P_Width','Predicate']
    with open('example.txt') as f:
        spamreader = csv.reader(f, delimiter=',')
        return [dict(zip(list_of_keys,row)) for row in spamreader]

print func()

Here since csv.reader accepts a delimiter argument and returns whole of your lines separated in one iterator you don't need to loop over your file and split it manually.

And if you want to preserve the order you can use collections.OrderedDict in both cases:

from collections import OrderedDict
import csv
def func():
    list_of_keys = ['S_Length','S_Width','P_Length','P_Width','Predicate']
    with open('example.txt') as f:
        spamreader = csv.reader(f, delimiter=',')
        return [OrderedDict(zip(list_of_keys,row)) for row in spamreader]

print func()
[OrderedDict([('S_Length', '2.1'), ('S_Width', '3.5'), ('P_Length', '1.4'), ('P_Width', '0.2'), ('Predicate', 'Iris')]), OrderedDict([('S_Length', '4.9'), ('S_Width', '3.0'), ('P_Length', '1.4'), ('P_Width', '0.2'), ('Predicate', 'Ilia')]), OrderedDict([('S_Length', '3.7'), ('S_Width', '3.2'), ('P_Length', '1.3'), ('P_Width', '0.2'), ('Predicate', 'Iridium')])]
like image 107
Mazdak Avatar answered Oct 23 '22 12:10

Mazdak


You only need to use split and do some iterations.

Try:

list_of_keys = ['S_Length','S_Width','P_Length','P_Width','Predicate']

list_of_dict = []

with open('mydata.txt', "r") as f:
    for line in f.readlines():
        parts = line.strip().split(",")
        mydict = {}
        i = 0
        for k in list_of_keys:
            mydict[k] = parts[i]
            i += 1
        list_of_dict.append(mydict)

print list_of_dict

Or:

list_of_keys = ['S_Length','S_Width','P_Length','P_Width','Predicate']

list_of_dict = []

with open('mydata.txt', "r") as f:
    for line in f.readlines():
        parts = line.strip().split(",")
        mydict = dict(zip(list_of_keys,parts))
        list_of_dict.append(mydict)

print list_of_dict
like image 2
Martín Muñoz del Río Avatar answered Oct 23 '22 10:10

Martín Muñoz del Río