Convert a file to a list of dictionaries

python read csv into dictionary of lists
python csv to dictionary header
python csv string to dictionary
convert csv to dictionary python
create a dictionary of lists with the keys being the heads of the csv file
how to read csv file to dictionary in python
how to put a csv file into a dictionary python
csvreader dictionary

I have file formatted like this:

MN_N3 net48 sout VSS VBN lvtnfet l=0.116u nf=1 M=1 nfin=4 
MN_N10 net082 net48 VSS VBN lvtnfet l=0.116u nf=1 M=1 nfin=4 
MN_N11 nclk_net CK VSS VBN lvtnfet l=0.068u nf=1 M=1 nfin=4 
MN_N9 SO SE net082 VBN lvtnfet l=0.116u nf=1 M=1 nfin=4 

I want to read it as list of dictionaries such that each line forms a dictionary like this

{'name': 'MN_N3' , 'source': 'net48' , 'gate': 'sout', 'Drain':'VSS'}

I have tried this:

d{'name':line.split(' ')[0], 'source':line.split(' ')[1], 'gate':line.split(' ')[2], 'drain':line.split(' ')[3]}

Which gave me:

File "", line 24
  d{'name':line.split(' ')[0], 'source':line.split(' ')[1], 'gate':line.split(' ')[2], 'drain':line.split(' ')[3]}
SyntaxError: invalid syntax

How can I do this / fix this error?

Here's a more manageable way of doing it. It will be much easier to update this code when your requirement changes, like adding lvtnfet also to the dictionary.

# Or file.readlines()
ls = ['MN_N3 net48 sout VSS VBN lvtnfet l=0.116u nf=1 M=1 nfin=4',
'MN_N10 net082 net48 VSS VBN lvtnfet l=0.116u nf=1 M=1 nfin=4',
'MN_N11 nclk_net CK VSS VBN lvtnfet l=0.068u nf=1 M=1 nfin=4',
'MN_N9 SO SE net082 VBN lvtnfet l=0.116u nf=1 M=1 nfin=4']

word_list = [[word for word in item.split(' ')[:4]] for item in ls ] # Only first 4 elements from the list

final_dict = {index:{'name': ls[0], 'source':ls[1], 'gate':ls[2], 'Drain': ls[3]} for index, ls in enumerate(word_list)}



 {0: {'Drain': 'VSS', 'gate': 'sout', 'name': 'MN_N3', 'source': 'net48'},
 1: {'Drain': 'VSS', 'gate': 'net48', 'name': 'MN_N10', 'source': 'net082'},
 2: {'Drain': 'VSS', 'gate': 'CK', 'name': 'MN_N11', 'source': 'nclk_net'},
 3: {'Drain': 'net082', 'gate': 'SE', 'name': 'MN_N9', 'source': 'SO'}}

And here's the expanded form for final_dict dict comprehension for reference.

final_dict = {}
for index, ls in enumerate(word_list):
    final_dict.update({index:{'name': ls[0], 'source':ls[1], 'gate':ls[2], 'Drain': ls[3]}})

Python : How to convert a list to dictionary ? –, Zip / unzip in python. Create a zip archive in python · How to unzip a file using Python? Get the list of all files in a zip file  Given a list, write a Python program to convert the given list to dictionary such that all the odd elements have the key, and even number elements have the value. Since python dictionary is unordered, the output can be in any order.

The most time-saving solution is to use Pandas. It will spare you from the misery of splitting strings, forming the dictionaries, and even having loops:

import pandas as pd
names = ['name' , 'source', 'gate', 'Drain']
pd.read_csv("your_file.dat", sep='\s+', header=None,
            usecols=range(len(names)), names=names).to_dict(orient='records')
#[{'name': 'MN_N3', 'source': 'net48', 'gate': 'sout', 'Drain': 'VSS'},
# {'name': 'MN_N10', 'source': 'net082', 'gate': 'net48', 'Drain': 'VSS'}, 
# {'name': 'MN_N11', 'source': 'nclk_net', 'gate': 'CK', 'Drain': 'VSS'},
# {'name': 'MN_N9', 'source': 'SO', 'gate': 'SE', 'Drain': 'net082'}]

Python: Read CSV into a list of lists or tuples or dictionaries, This list can be a list of lists, list of tuples or list of dictionaries. Now let's see how to import the contents of this csv file into a list. each row of this 2D array and for each row we converted that to a tuple, then append it to a list. I have a list of dictionaries, looking some thing like this: list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}] and so on. There may be more documents in the list. I need to convert these to one JSON document, that can be returned via bottle, and I cannot understand how to do this. Please

You can't make dictionaries like that. You would have to use:

d = {'name': line.split(' ')[0], ...}

A better way of doing this, however, would be to use a for-loop.

for line in input.split('\n'): # \n is the new line character
    for item in line.split(' '):

This gives you every single item, and you could add each item to a dictionary by using a counter (or the enumerate function) in the inner for-loop. You could then create a list of the names and access the word by the counter's index.

Python, Conversion from one data type to other is essential in various facets of programming. Be it development or competitive programming. Hence knowledge of it is  just read the file line by line, and for each line of string, use `split(', ') to get a list of first and second item in the line, then you can store the two strings in a dictionary, and you can convert the second string into a integer if necessary.

f = open('tp.txt','r').readlines()
for line in f:
    print({'name':line.split(' ')[0], 'source':line.split(' ')[1], 'gate':line.split(' ')[2], 'drain':line.split(' ')[3]})

This will print dictionaries. You can change the print to an assignment if you want to save it .

Python - Convert List of Dictionaries to List of Lists, Is it Worth to Learn Python in 2020? Voting System Project Using Django Framework · LRU Cache in Python using OrderedDict · Writing CSV files in Python  Following conversions from list to dictionary will be covered here, Convert a List to Dictionary with same values; Convert List items as keys in dictionary with enumerated value; Convert two lists to dictionary; Convert a list of tuples to dictionary; Convert a List to Dictionary with same values. Suppose we have a list of strings i.e.

Convert a CSV to a Dictionary in Python, Think of the list as the row containing the values, and the dictionary as the column. Function to convert a csv file to a list of dictionaries. I have file formatted like this: MN_N3 net48 sout VSS VBN lvtnfet l=0.116u nf=1 M=1 nfin=4 MN_N10 net082 net48 VSS VBN lvtnfet l=0.116u nf=1 M=1 nfin=4 MN_N11 nclk_net CK VSS VBN lvtnfet l=0.068

Using dictionaries to store data as key-value pairs, Both the dictionary and list are ubiquitous for representing real-world data. when manually creating dictionary objects and converting real-world data into API will return a text file (in JSON format) that can be turned into a Python dictionary: Convert list of dictionaries to csv file. Ask Question Asked 1 year, 4 months ago. Active 1 year, 4 months ago. Viewed 2k times 2. 1. I have a list of dictionaries of

How to convert a dictionary to a list in Python, How do you convert an integer to a file? :-) Of course, you might think of a file descriptor, but it isn't really obvious from the form of your question. “Convert an A​  In this tutorial, we will learn how to convert a dictionary into a list in Python with three different methods. A Dictionary is an unordered sequence that is mutable. Certainly, it is used for more flexible operations.