Making Python Dictionary from a Text File With Multiple Keys

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



Leave a reply



Submit