Convert text file into dictionary with multiple keys in python
You want to itterate through the lines and split them on :,
Once you find # you will want to add the dict to a output list
something like this should work
with open("order.txt", "r") as f:
res = []
start = dict()
for line in f:
line = line.strip()
if line[0] == '#':
res.append(start)
start = dict()
else:
add = line.split(":")
start[add[0]] = add[1]
res.append(start)
print(res)
Making python dictionary from a text file with multiple keys
You can use a defaultdict
.
from collections import defaultdict
data = defaultdict(list)
with open("file.txt", "r") as f:
for line in f:
line = line.split()
data[line[0]].extend(line[2:])
How to read from a text file and store multiple values to a key in dictionary
dicta = dict()
with open("yourfile.txt", "r") as file:
for i in file:
line, *lines = i.split()
dicta[line] = lines
.split() will only split it at the spaces
the dict look like this
{'ABC,_XYZ': ['45.1976844', '-69.458819'],
'AWA,_WES': ['44.946356', '-90.315969'],
'AXA,_WWA': ['36.3055851', '-104.2588701']}
here line takes the first value and *lines just takes the rest
UPDATE
dicta = dict()
with open("yourfile.txt", "r") as file:
for i in file:
line, *lines = i.split()
if line in dicta:
dicta[line] += lines
else:
dicta[line] = lines
dicta = dict()
with open("yourfile.txt", "r") as file:
for w,i in enumerate(file):
line, *lines = i.split()
if line in dicta:
dicta[w] = lines
else:
dicta[line] = lines
dicta = list()
with open("yourfile.txt", "r") as file:
for w,i in enumerate(file):
line, *lines = i.split()
dicta.append((line,lines))
Creating a text file using keys from dictionary with multiple values
Here is a solution iterating through the dictionary's keys and values respectively using the in-built items()
method, along with f-strings.
sol = {'Uranus': ['2750', '3000', '2880'],
'Mercury': ['46', '70', '57'],
'Earth': ['147', '152', '150'],
'Venus': ['107', '109', '108'],
'Mars': ['205', '249', '228'],
'Saturn': ['1350', '1510', '1430'],
'Jupiter': ['741', '817', '779'],
'Neptune': ['4450', '4550', '4500'],
'Pluto': ['4440', '7380', '5910']}
with open(OUTPUT_FILE, "w") as s:
for k, v in sol.items():
s.write(f"{k},{','.join(v)}\n")
Converting a text file to python dictionary - one key and multiple values - with exclusion of one field
You don't explain what difficulties you face.
However, from that sample of tab-delimited text, and you want to have dict like:
{'John': ['27', 'doctor', 'Chicago'], 'Nick': ['33', 'engineer', 'Washington']}
If that's the output you want to reach, then I modified your code a bit.
myfile = open ("filename", "r")
d = { }
for line in myfile:
x = line.strip().split("\t")
key, values = x[1], x[2:]
d.setdefault(key, []).extend(values)
print(d)
Turning text file into dictionary when the same keys appear multiple times
Try this .get(key)
method of the dictionary will return None
if the key doesn't exit otherwise return the value for the key. so you can use it in if condition.
I hope this is what you want by reading your question.
filename = "text.txt"
with open(filename, encoding="utf-8") as f_skipped:
result = {}
for line in f_skipped:
try:
k, v = line.split()
except ValueError:
pass
else:
if result.get(k) is None:
result[k] = v
print(result)
Output
py code.py
{'tomato': '7000', 'prunes': '892', 'carrot': '600'}
Convert txt file with multiple columns to dictionary
Dictionaries in Python cannot have duplicate keys, so the closest thing you could do would be to store a list of values associated with each key.
Your file is composed of character separated values, so using Python's csv
module would make parsing the file into separate fields trivial.
Here's one way to accomplish what you want. Note that you could also use the collections.defaultdict
class, which was added to Python v2.5, instead of defining one of your own as shown below:
import csv
from pprint import pprint
class ListDict(dict):
""" Dictionary who's values are lists. """
def __missing__(self, key):
value = self[key] = []
return value
filename = 'multi_col.csv'
lstdct = ListDict()
with open(filename, 'rb') as csvfile:
for row in csv.reader(csvfile, delimiter='|'):
key, value = row[:2]
lstdct[key].append(value)
pprint(lstdct) # -> {'AM': ['75019', '75021', '75015']}
Related Topics
Valueerror: Invalid \Escape Unable to Load Json from File
List of the Most Recently Updated Files in Python
How to Read Image Data from a Url in Python
How to Get Rid of the B-Prefix in a String in Python
Running Two Python Scripts With Bash File
Output the Same Amount of Rows as Asterisks Using For-Loop
Keras + Tensorflow and Multiprocessing in Python
String Concatenate Typeerror: Can Only Concatenate Str (Not "Int") to Str"
Python Command Not Working in Command Prompt
Python - How to Fix "Valueerror: Not Enough Values to Unpack (Expected 2, Got 1)"
Filtering Dataframe Using the Length of a Column
Using Continue in a Try and Except Inside While-Loop
Package Only Binary Compiled .So Files of a Python Library Compiled With Cython
How to Use Ffmpeg in a Python Function
Most Efficient Way to Forward-Fill Nan Values in Numpy Array
Calculate Final Letter Grade in Python Given 4 Test Scores
Python Does Not Match Format '%Y-%M-%Dt%H:%M:%S%Z.%F'
Django: Calling .Update() on a Single Model Instance Retrieved by .Get()