Dictionary to Tab Delimited Text File for Particular Schema - python-3.x

I have a dictionary of the form:
data = {'a':'one','b':'two','c':'three'}
I want to convert this to a tab delimited text file such that the file reads as:
a b c one two three.
I tried:
import json
data = {'a':'one','b':'two','c':'three'}
with open('file.txt', 'w') as file:
file.write(json.dumps(data))
However the resulting file just reads as ('a':'one','b':'two','c':'three'). I knew it wouldn't be as simple as that, and I'm sure it's not complex, but I just can't seem to figure this one out.

data = {'a':'one','b':'two','c':'three'}
s = ""
for x in data.keys():
s += x
s += "\t"
for x in data.values():
s += x
s += "\t"
print(s)
with open('file.txt', 'w') as file:
file.write(s)
Dictionary is a structure that's designed for when a one-to-one association between values exist. Here is a link to further discussions on how it compares with other structures.
Therefore it makes sense to print the key:value pair together to preserve that association. Thus the default behaviour of print(data) or in your case file.write(data) when data is a dictionary is to output {'a': 'one', 'b': 'two', 'c': 'three'}.
The key1, key2, ... value1, value2 ... type of output format you request is not typical for a structure like dictionary, therefore a more "manual" approach like the one above involving two loops is required.
As for json, its usage is really not that relevant in the code you provided, maybe it is used in other parts of your code base when a json specific output format is required. You can read more on json here to know that it is a format independent of the python programming language.

Related

How to convert dictionary values from string to variable and access as nested dictionary?

Is it possible to convert dictionary values from string to a variable to access the nested dictionary?
I've seen some instances where people are using exec() to do regular dictionaries keys; but have not seen it in cases of nested dictionary.
My goal is to open text file, parse the data and create a single dictionary with the info from the text file, so that when someone edits it, it will automatically update when user restarts program instead of having to recreate executable.
material_txt:
#enter descriptions below for main dictionary keys:
'Description'
'Description1'
'Description2'
#will be used as nested dictionaries
Test = {'':"Nested_Test", '1':"Nested_Test1", '2': "Nested_Test2"}
Nested = {'':"Nested", '1':"Nested1", '2': "Nested"}
Dictionary= {'':"Nested_Dictionary", '1':"Nested_Dictionary1", '2': "Nested_Dictionary2"}
The descriptions should correspond to the dictionaries as follows;
Description -> Test
Description1 -> Nested
Description2 -> Dictionary
Code:
descriptionList = []
with open(material_txt,'r') as nested:
for line in nested.readlines():
if line.startswith("\'"):
#works with descriptions from text file
print("Description:{0}".format(line))
description = line.lstrip("\'")
descriptionList .append(description.rstrip("\'\n"))
elif line.startswith("#"):
print("Comment:{0}".format(line))
pass
elif line.startswith("\n"):
print("NewLine:{0}".format(line))
pass
else:
# This works with nested dictionaries from the text file
line.rstrip()
dictionaryInfo = line.split("=")
#Line below - dictionaryInfo[0] should be variable and not a string
#exec("dictionary[dictionaryInfo[0]] = eval(dictionaryInfo[1])")
dictionary[dictionaryInfo[0]] = eval(dictionaryInfo[1])
for descriptions,dictionaries in zip(descriptionList,dictionary.items()):
#nested dictionary
mainDictionary[descriptions] = dictionaries[0]
so when I call below I get the desired nested dictionary:
print(mainDictionary ['Description1'])
result ---> {'':"Nested", '1':"Nested1", '2': "Nested"}
I'm aware I could run the text file as a python module, but I would rather just leave it as a text file and do parsing in my program.
It's not exactly clear to me what you are trying to do. But usually for this task people use JSON:
>>> import json
>>> main_dict = json.loads('{"outer1": {"inner1a": 7, "inner1b": 9}, "outer2": 42}')
>>> main_dict
{'outer2': 42, 'outer1': {'inner1b': 9, 'inner1a': 7}}
Does this help?

How to loop through a list of dictionaries and write the values as individual columns in a CSV

I have a list of dictionaries
d = [{'value':'foo_1', 'word_list':['blah1', 'blah2']}, ...., {'value': 'foo_n', 'word_list':['meh1', 'meh2']}]
I want to write this to a CSV file with all the 'value' keys in one column, and then each individual word from the "value"'s word_list as its own column. So I have the first row as
foo_1 blah_1 blah_2
and so on.
I don't know how many dictionaries I have, or how many words I have in "word_list".
How would I go about doing this in Python 3?
Thanks!
I figured out a solution, but it's kind of messy (wow, I can't write a bit of code without it being in the "proper format"...how annoying):
with open('filename', 'w') as f:
for key in d.keys():
f.write("%s,"%(key))
for word in d[key]:
f.write("%s,"%(word))
f.write("\n")
You can loop through the dictionaries one at a time, construct the list and then use the csv module to write the data as I have shown here
import csv
d = [{'value':'foo_1', 'word_list':['blah1', 'blah2']}, {'value': 'foo_n', 'word_list':['meh1', 'meh2']}]
with open('test_file.csv', 'w') as file:
writer = csv.writer(file)
for val_dict in d:
csv_row = [val_dict['value']] + val_dict['word_list']
writer.writerow(csv_row)
It should work for word lists of arbitrary length and as many dictionaries as you want.
It would probably be easiest to flatten each row into a normal list before writing it to the file. Something like this:
with open(filename, 'w') as file:
writer = csv.writer(file)
for row in data:
out_row = [row['value']]
for word in row['word_list']:
out_row.append(word)
csv.writerow(out_row)
# Shorter alternative to the two loops:
# csv.writerow((row['value'], *row['word_list']) for row in data)

How to assign number to each value in python

I am comparatively new to python and data science and I was working with a CSV file which looks something like:
value1, value2
value3
value4...
Thing is, I want to assign a unique number to each of these values in the csv file such that the unique number acts as the key and the item in the CSV acts as the value like in a dictionary.
I tried using pandas but if possible, I wanted to know how I can solve this without using any libraries.
The desired output should be something like this:
{
"value1": 1,
"value2": 2,
"value3": 3,
.
.
.
and so on..
}
Was just about to talk about pandas before I saw that you wanted to do it in vanilla Python. I'd do it with pandas personally, but here you go:
You can read in lines from a file, split them by delimiter (','), and then get your word tokens.
master_dict = {}
counter = 1
with open("your_csv.csv", "r") as f:
for line in f:
words = line.split(',') # you may or may not want to add a call to .strip() as well
for word in words:
master_dict[counter] = word
counter += 1

Dictionary to a txt file

I am trying to write a dictionary to a .txt file. I haven't found an efficient way to add multiple values for keys to a text doc.
players = {}
def save_roster(players):
with open("Team Roster.txt", "wt") as out_file:
for k, v in players.items():
out_file.write(str(k) + ', ' + str(v) + '\n\n')
display_menu()
I have a dictionary that has multiple values for the key. This part of the program leave me with:
Bryce, <__main__.Roster object at 0x00000167D6DB6550>
Where the out put i am aiming for is:
Bryce, 23, third, 23
Python doesn't inherently understand how to print an object. You need to define the __str__ method in order to tell python how to represent your object as a string; otherwise it will default to the representation you're getting. In your case, I might go with something like
def __str__(self):
return str(self.position)+", "+str(self.jersey)
or whichever attributes you want to print.
And to read the data back in from the text file:
with open("Team Roster.txt", "r") as in_file:
for line in in_file:
player = Roster(*(line.split(", "))
#do something with player, like store it in a list
Assuming Roster.__init__() is set up appropriately, i.e. a Roster object is initialized by passing in the parameters in each line of the file in order.

Convert string from external file to Python dictionary

I've looked around but I haven't really found a solution. I have external TXT file that contains strings separated by commas, each "item" is on new line:
item1: value1
item2: value2
etc. you get the idea.
I am creating script that works with dictionary and I need to convert the file to Python dictionary. I'm still a newbie so I'm kinda lost.
I have tried this which I found here String to dictionary :
dict((key, None) for key in string.split(': '))
But I am unable to figure out how to replace 'None' with sth that represents Value of a Key. I did try dict((key, value)) but 'value' is not recognized.
You can solve it like this:
dict((key, value) for key, value in [string.split(': ')])
Note that this will fail if there are multiple ': ''s in the string.
This peace of code works like the following:
>>> string = 'hello: world'
>>> string.split(': ')
['hello', 'world']
>>> a, b = string.split(': ')
>>> a
'hello'
>>> b
'world'
The values will be strings this way. If they should be for example integers, use (key, int(value)). This, also, is not failsafe if there are none-integer values.
Remark: As of Python 2.7, which you tagged your question with, you can use dictionary comprehensions. This is a bit cleaner:
{key: value for key, value in [string.split(': ')]}
This will, however, get you a lot of dictionaries of size 1. I think you'll need something like this:
{key: value for line in fileobject.readlines() for key, value in [line.split(': ')]}
You could also use the split directly:
dict(tuple(string.split(': ')) for string in fileobject.readlines())
I asked around on #Python (FreeNode) to help me with this as well and there seems to be more "neat" solution.
fileobject = open('text.txt', 'r')
fdict = {}
for line in fileobject.readlines():
for key, value in [line.split(':')]:
fdict[key] = value
This seems more clean to me and more understandable.

Resources