I have a list like this:
d = [{string1:float1,string2: float2},{string1:float3,string2:float4},...]
I tried:
import json
with open("outputfile.txt","w") as f:
json.dump(d,f)
then all the content is in one line like:
[{string1:float1,string2: float2},{string1:float3,string2:float4},{string1:float5,string2:float6},...]
what I want is for each (key:valve) starts a newline,like
[{string1:float1,
string2:float2},
{string1:float3,
string2:float4},
...
endstring:endfloat}]
how can I do this ? or I can just replace every "," to ",\n"? The order does not matter much, but if possible, a "sorted" result will be appreciated.
As per https://docs.python.org/2.7/library/json.html:
json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4, separators=(',', ': '))
should result in:
{
"4": 5,
"6": 7
}
Python 3.x solution is identical.
Note the use of dumps as opposed to dump.
Updated solution:
for dict in d:
with open("outputfile.txt","a") as f:
json.dump(dict, f)
f.write('\n')
or
for dict in d:
with open("outputfile.txt","a") as f:
json.dump(dict, f, indent=4)
Related
I've a dictionary dic = {(1,2,3): 3, (2,3,4): 2, (3,4,8): 5}
I want it to be saved it in the text file output.txt with the specified format
1 2 3 (3)
2 3 4 (2)
3 4 8 (5)
modify the following code for this task
dic = {(1,2,3): 3, (2,3,4): 2, (3,4,8): 5}
with open('output.txt', 'w') as file:
file.write(str(dic))
Iterate the dictionary and write content to text file.
Ex:
dic = {(1,2,3): 3, (2,3,4): 2, (3,4,8): 5}
with open('output.txt', 'w') as file:
for k, v in dic.items(): #Iterate dic
file.write("{} ({}) \n".format(" ".join(map(str, k)), v)) #write to file.
dic = {(1,2,3): 3, (2,3,4): 2, (3,4,8): 5}
with open('output.txt', 'w') as file:
for k, v in dic.items(): #Iterate dic
file.write("{} ({}) \n".format(k, v)) #write to file.
Here we just have to pass the key and value to the format function. I dont think any other operations has to be done on this.
str.format() is one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. This method allows to concatenate elements within a string through positional formatting.
I have a dictionary in python in this way
my_dict = {'1':['a','b','c'], '2':['d','e','f']}
and i want to write a csv file in which it is displayed as it follows
1, a b c
2, d e f
because it is parsed by another application in this specific format.
Is there any way to it?
This is a way to do it:
my_dict = {'1':['a','b','c'], '2':['d','e','f']}
with open('data.csv', 'w') as f:
f.write('\n'.join([("%s, %s" % (k,' '.join(my_dict[k]))) for k in my_dict])
my_dict = {'1':['a','b','c'], '2':['d','e','f']}
from operator import itemgetter
import csv
with open('data.csv','w') as f:
a = csv.writer(f, delimiter = ',', lineterminator='\n')
for k,v in sorted(my_dict.items(), key=itemgetter(0)):
a.writerow([k,' ' + ' '.join(v)])
data.csv
1, a b c
2, d e f
I just want to write dictionary values into text file line wise line.I can write whole dictionary in to the file using:
log_disk={}
log=open('log.txt','w')
log.write(str(log_disk))
log.close()
Any help will be appreciated.In addition I want to avoid those keys which have value 'Empty' while writing into the file.
Just loop over the values then:
with open('log.txt','w') as log:
for value in log_disk.values():
log.write('{}\n'.format(value))
Write data as JSON unformatted string
You may dump the data as JSON, without formatting JSON data it is written on one line.
Do not forget to append newline:
>>> import json
>>> data = {}
>>> with open(fname, "a") as f:
... json.dump(data, f)
... f.write("\n")
...
Try with another data:
>>> data = {"a": "aha", "b": "bebe"}
>>> with open(fname, "a") as f:
... json.dump(data, f)
... f.write("\n")
...
It does not have to be dictionary, lists are working too:
>>> data = range(10)
>>> data
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> with open(fname, "a") as f:
... json.dump(data, f)
... f.write("\n")
...
Reading data line by line
>>> with open(fname) as f:
... for line in f:
... print json.loads(line)
...
{}
{u'a': u'aha', u'b': u'bebe'}
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
You just need to convert log_disk.values() to a list and you can write them directly
with open(filename) as openfile:
json.dump(list(log_disk.values()), file)
I have looked at other questions on SO like this one but they are too techy for me to understand (only been learning a few days).
I am making a phonebook and i am trying to save a dictionary like so,
numbers = {}
def save(a):
x = open("phonebook.txt", "w")
for l in a:
x.write(l, a[l])
x.close()
But i get error write() only takes 1 argument and obv im passing 2, so my question is how can i do this in a beginner freindly way and could you describe it in a non techy way.
Thanks a lot.
It's better to use json module for dumping/loading dictionary to/from a file:
>>> import json
>>> numbers = {'1': 2, '3': 4, '5': 6}
>>> with open('numbers.txt', 'w') as f:
... json.dump(numbers, f)
>>> with open('numbers.txt', 'r') as f:
... print json.load(f)
...
{u'1': 2, u'3': 4, u'5': 6}
While JSON is a good choice and is cross-language and supported by browsers, Python has its own serialization format called pickle that is much more flexible.
import pickle
data = {'Spam': 10, 'Eggs': 5, 'Bacon': 11}
with open('/tmp/data.pickle', 'w') as pfile:
pickle.dump(data, pfile)
with open('/tmp/data.pickle', 'r') as pfile:
read_data = pickle.load(pfile)
print(read_data)
Pickle is Python-specific, doesn't work with other languages, and be careful to never load pickle data from untrusted sources (such as over the web) as it's not considered "safe".
Pickle works for other data types too, including instances of your own classes.
You need to use the json module and JSONEncode your dict, then you can use the module to write the new object to file.
When you read the file, you need to JSONDecode to convert it back into a python dict.
>>> import json
>>> d = {1:1, 2:2, 3:3}
>>> d
{1: 1, 2: 2, 3: 3}
>>> json.JSONEncoder().encode(d)
'{"1": 1, "2": 2, "3": 3}'
>>> with open('phonebook.txt', 'w') as f:
f.write(json.JSONEncoder().encode(d))
>>> with open('phonebook.txt', 'r') as f:
print f.readlines()
['{"1": 1, "2": 2, "3": 3}']
I am trying to make a dictionary from a csv file in python, but I have multiple categories. I want the keys to be the ID numbers, and the values to be the name of the items. Here is the text file:
"ID#","name","quantity","price"
"1","hello kitty","4","9999"
"2","rilakkuma","3","999"
"3","keroppi","5","1000"
"4","korilakkuma","6","699"
and this is what I have so far:
txt = open("hk.txt","rU")
file_data = txt.read()
lst = [] #first make a list, and then convert it into a dictionary.
for key in file_data:
k = key.split(",")
lst.append((k[0],k[1]))
dic = dict(lst)
print(dic)
This just prints an empty list though. I want the keys to be the ID#, and then the values will be the names of the products. I will make another dictionary with the names as the keys and the ID#'s as the values, but I think it will be the same thing but the other way around.
Use the csv module to handle your data; it'll remove the quoting and handle the splitting:
results = {}
with open('hk.txt', 'r', newline='') as txt:
reader = csv.reader(txt)
next(reader, None) # skip the header line
for row in reader:
results[row[0]] = row[1]
For your sample input, this produces:
{'4': 'korilakkuma', '1': 'hello kitty', '3': 'keroppi', '2': 'rilakkuma'}
You can use csv DictReader:
import csv
result={}
with open('/tmp/test.csv', 'r', newline='') as f:
for d in csv.DictReader(f):
result[d['ID#']]=d['name']
print(result)
# {'1': 'hello kitty', '3': 'keroppi', '2': 'rilakkuma', '4': 'korilakkuma'}
You can use a dictionary directly:
dictionary = {}
file_data.readline() # skip the first line
for key in file_data:
key = key.replace('"', '').strip()
k = key.split(",")
dictionary[k[0]] = k[1]
try this or use any library to read the file.
txt = open("hk.txt","rU")
file_data = txt.read()
file_lines = file_data.split("\n")
lst = [] #first make a list, and then convert it into a dictionary.
for linenumber in range(1,len(file_lines)):
k = file_lines[linenumber].split(",")
lst.append((k[0][1:len(k[0])-1],k[1][1:len(k[1])-1]))
dic = dict(lst)
print(dic)
but you can use the dict directly as well.