read data from file into dictionaries

read dictionary from text file python
python read list of dictionaries from file
load text file into dictionary python
converting text file to dictionary python
python read lines from file into dictionary
python dictionary
python create dictionary from text file
text to dictionary python

Lets say that i have a file containing information in each line and each line i want to convert in a dictionary. In the dictionary there will be one string, two integers and two lists. kinda like this: Q1 = { "string" : "name", "integer1" : 1, "integer2" : 2, "list1" : [a,b,c,d], "list2": [] } Now the file could be a txt file or not. Lets say its a txt file and every line would provide a dictionary. I am the one to write the file so I can have it in any format i want. I thought this format for each line of the file.txt: name,1,2,(a/b/c), () so the first thing is the string, the second is integer1, then integer2, list1 and list2. Each element of the dictionary separated with a comma and the elements of the lists inside parenthesis and separated with a slash ("/"). Obviously if you think there is a better idea for how the file.txt should like please let me know :) the first list i want it to be dynamic. that means some lines may contain more characters inside the parenthesis () and the second list i want it to always be empty cause i am putting things there later in my code. Each line is a dictionary and each dictionary is an element in a list i want to create. So i want to have a list of dictionaries.

I tried to open a file and play with the split function but the format of the txt file is more complicated than i thought and never got to read the file and save it into a list of dictionaries

#the file.txt should look like this:
name1,5,6,(a1/a2/a3), ()
name2,7,8,(a2/a3/a4/a5), ()

#the python code i tried:
def init():
    myList=[]
    with open("file.txt") as f:
        for line in f:
            d={}
            d = dict(line.strip().split(',', 4))
            myList[line]=d
return(myList)        

list=[]
list=init();

inside file1.txt

hey1,5,6,(a1/a2/a3), () hey2,7,8,(a2/a3/a4/a5), ()

You can use below code it will generate a new dictionary for each line and at last all the dictionary inside the dict_main.

index1=['string1','integer1','integer2','list1','list2']
dict_main={}
with open ('file1.txt') as f:
    count=0
    for line in f:
        dict1={}
        lst1=line.strip().split(',')
        dict1[index1[0]]=lst1[0]
        dict1[index1[1]]=int(lst1[1])
        dict1[index1[2]]=int(lst1[2])
        dict1[index1[3]]=lst1[3][1:-1].strip().split('/')
        dict1[index1[4]]=[]
        count+=1
        dict_main['dict'+str(count)]=dict1
print(dict_main)

Result

{'dict1': {'integer2': 6, 'list2': [], 'integer1': 5, 'list1': ['a1', 'a2', 'a3'], 'string1': 'hey1'}, 'dict2': {'integer2': 8, 'list2': [], 'integer1': 7, 'list1': ['a2', 'a3', 'a4', 'a5'], 'string1': 'hey2'}}

How to create a Python dictionary from text file?, Assuming a following text file (dict.txt) is present1 aaa2 bbb3 cccFollowing Python code reads the file using open() function. Each line as string is split at s CSV raw data is not utilizable in order to use that in our Python program it can be more beneficial if we could read and separate commas and store them in a data structure. We can convert data into lists or dictionaries or a combination of both either by using functions csv.reader and csv.dictreader or manually directly

Check this... without using any package.

with open("test.txt") as f:
  lines = [ line.strip().split(",") for line in f ]
  lines = [{ 
        "string": line[0], 
        "integer1": int(line[1]), 
        "integer2": int(line[2]), 
        "list1": [l for l in line[3].strip("()").split("/")],
        "list2": [l for l in line[4].strip("()").split("/")],
  } for line in lines ]
  print(lines)

Python - Read a text file into a dictionary, Given the following data in a text file the task is to convert it into a Python dict import json filename = 'commands.txt' commands = {} with  Ok well I have a good understanding of python. I am working on a project that sorts files and I need a place to store the extention:folderToPutIn And working from text files is kind of time taking so I want to use dictionaries. I know how to open and do operations with files. (I have been pythoning for 1 year).

Python: convert a text file into a dictionary, How to read a dictionary from a file in Python. Reading and parsing a text file that has the format of a dictionary results in a dictionary data structure in Python. Reading an Excel (xlsx) File to a Python Dictionary. Now, before we learn how to read multiple xlsx files we are going to import data from Excel into a Python dictionary. It’s quite simple, but for the example below, we need to know the column names before we start.

You can also use regex and avoid using "/" character if you want, like this:

import re    
txt1 = "name1,5,6,[a1,a2,a3],[]"
regex = "([a-zA-Z0-9]*),([0-9]+),([0-9]+),\[(.*)\],\[(.*)\]"
matches = re.match(regex, txt1)
dict1 = {"string": matches.group(1), "integer1": matches.group(2), "integer2": matches.group(3),
         "list1": matches.group(4).split(","), "list2": matches.group(5).split(",")}

The result being:

{'string': 'name1', 'integer1': '5', 'integer2': '6', 'list1': ['a1', 'a2', 'a3'], 'list2': ['']}

How to read a dictionary from a file in Python, Do you know how to read files? Here's another thing to think about and to go investigate how to do: how do you separate the key from the value in  Assuming a following text file (dict.txt) is present. 1 aaa 2 bbb 3 ccc. Following Python code reads the file using open() function. Each line as string is split at space character.

How to convert Text file contents into a dictionary., If you truly want to write the contents of a Python dictionary to a file in the format you've described (as To read that back you could use something like: data = dict(); with open(myfile) as raw_data: for item if raw_data: if ':' in item: key,value  Reading Dictionary Items The Dictionary is a collection. We can use the foreach loop to go through all the items and read them using they Key and Value properties. foreach (KeyValuePair<string, Int16> author in AuthorList)

How to write a dictionary to a file in Python, How can we read the rainfall data in this file and make a plot of the values? The most straightforward solution is to read the file line by line, and for each line split​  import json # open output file for reading with open('listfile.txt', 'r') as filehandle: basicList = json.load(filehandle) Conclusion. The different methods shown above range from simple writing/reading data up to dumping/loading data via binary streams using pickle and JSON.

Files, Strings, and Dictionaries, In this example we try to open the data file for reading. If it succeeds, we use the read() method to read the file contents as a string into the variable mydata  Loading a .csv file into a pandas DataFrame. Okay, time to put things into practice! Let’s load a .csv data file into pandas! There is a function for it, called read_csv(). Start with a simple demo data set, called zoo! This time – for the sake of practicing – you will create a .csv file for yourself! Here’s the raw data:

Comments
  • Please provide current output and what you expect the output to be (for the return statements) as well as any errors you encounter.
  • Using Pandas with a csv file is usually the easiest for this sort of thing. Look at reading in a csv: pandas.pydata.org/pandas-docs/stable/generated/… And converting the dataframe to a dictionary: pandas.pydata.org/pandas-docs/stable/generated/…
  • And if pandas is overkill for your usecase, use csv.DictReader instead, which reads a line of comma separated values into a dictionary
  • @KuboMD right now i have these dictionaries hard coded in my python file and instead of hard coding them in my .py i want to read them from a file. i don't expect a specific output other than how a list of dictionaries should be like. in my code i use this list of dictionaries to import and extract elements of this list based on an algorithm i am using. doesn't matter what i am doing with this list. i just want a list of dictionaries that are written in a separate file than my .py file. there no errors just not in the format i want it to be.
  • i will check pandas. thanks
  • You could make your first list comprehension into a generator comprehension and thus save (potentially a lot) of memory. Also, no ; needed in Python.