How to write output with fout function in properly?How to merge two dictionaries in a single expression?How do I check if a list is empty?How do I check whether a file exists without exceptions?How to flush output of print function?How can I safely create a nested directory?Using global variables in a functionHow do I sort a dictionary by value?How to make a chain of function decorators?How to make a flat list out of list of listsHow do I list all files of a directory?

MinionPro is erroneous

In SQL Server, why does backward scan of clustered index cannot use parallelism?

Why is transplanting a specific intact brain impossible if it is generally possible?

Why did the RAAF procure the F/A-18 despite being purpose-built for carriers?

A tool to replace all words with antonyms

Am I overreacting to my team leader's unethical requests?

Y2K... in 2019?

How many different ways are there to checkmate in the early game?

What gave Harry Potter the idea of writing in Tom Riddle's diary?

The equation of motion for a scalar field in curved spacetime in terms of the covariant derivative

Visa National - No Exit Stamp From France on Return to the UK

How does 'AND' distribute over 'OR' (Set Theory)?

Is refreshing multiple times a test case for web applications?

Why does Intel's Haswell chip allow FP multiplication to be twice as fast as addition?

Te-form and かつ and も?

Can a fight scene, component-wise, be too complex and complicated?

Can the Action some concentration spells grant be used in Attacks of Opportunity with the War Caster feat?

DeclareMathOperator and widearcarrow with kpfonts

Are there any financial disadvantages to living significantly "below your means"?

What are the conventions for transcribing Semitic languages into Greek?

Is it legal for a company to enter an agreement not to hire employees from another company?

Is TA-ing worth the opportunity cost?

Is it okay for a ticket seller to grab a tip in the USA?

What costs less energy? Roll or Yaw?



How to write output with fout function in properly?


How to merge two dictionaries in a single expression?How do I check if a list is empty?How do I check whether a file exists without exceptions?How to flush output of print function?How can I safely create a nested directory?Using global variables in a functionHow do I sort a dictionary by value?How to make a chain of function decorators?How to make a flat list out of list of listsHow do I list all files of a directory?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I'm trying to read and write a file with python file system but I'm having some problems. I believe that the reading/opening function is correct but the writing one is giving me a hard time.



I'm doing it inside a function that inverts a dictionary and I want it to read the dictionary from a text file instead of doing it inside the code, here's how I called it(not beautifully but works):



d = fin = open('dict.txt')


However, when it comes to writing the inverted dictionary to a file I'm failing miserably. The function call that prints the inverted dict is invert_dict(d) so I thought that I should try to write it like this:



invert_dict(d) = fout = open('output.txt', 'w')


Which is clearly wrong but that's what I got from reading a book. Here's my raw invert dictionary function :



def invert_dict(d):
print(' the dictionary is n' , d)
inverse = dict()
for key in d:
val = d[key]
for i in val:
if i not in inverse:
inverse[i] = [key]
else:
inverse[i].append(key)
return inverse
d='vowels':['a','e','i','o','u'], 'letters':['a','b','c','d']
print(invert_dict(d))


How should I improve my code? Thanks in advance.










share|improve this question





















  • 1





    if you want it to be properly, first use 'with open' construct (pythonforbeginners.com/files/…); also try to separate functionality - avoid creating superclass or supermethod in this case that does everything

    – Drako
    Mar 27 at 8:36











  • @Drako Sweet, so instead of using the ugly d = fin = open('dict.txt') I can use with open(“dict.txt”) as file:? Appreciate it! Regarding writing my output in a text file, thoughts? :)

    – Bruno
    Mar 27 at 8:43












  • @Bruno see my edit?

    – U10-Forward
    Mar 27 at 8:45






  • 1





    @U9-Forward Yes sir, thanks

    – Bruno
    Mar 27 at 8:50

















1















I'm trying to read and write a file with python file system but I'm having some problems. I believe that the reading/opening function is correct but the writing one is giving me a hard time.



I'm doing it inside a function that inverts a dictionary and I want it to read the dictionary from a text file instead of doing it inside the code, here's how I called it(not beautifully but works):



d = fin = open('dict.txt')


However, when it comes to writing the inverted dictionary to a file I'm failing miserably. The function call that prints the inverted dict is invert_dict(d) so I thought that I should try to write it like this:



invert_dict(d) = fout = open('output.txt', 'w')


Which is clearly wrong but that's what I got from reading a book. Here's my raw invert dictionary function :



def invert_dict(d):
print(' the dictionary is n' , d)
inverse = dict()
for key in d:
val = d[key]
for i in val:
if i not in inverse:
inverse[i] = [key]
else:
inverse[i].append(key)
return inverse
d='vowels':['a','e','i','o','u'], 'letters':['a','b','c','d']
print(invert_dict(d))


How should I improve my code? Thanks in advance.










share|improve this question





















  • 1





    if you want it to be properly, first use 'with open' construct (pythonforbeginners.com/files/…); also try to separate functionality - avoid creating superclass or supermethod in this case that does everything

    – Drako
    Mar 27 at 8:36











  • @Drako Sweet, so instead of using the ugly d = fin = open('dict.txt') I can use with open(“dict.txt”) as file:? Appreciate it! Regarding writing my output in a text file, thoughts? :)

    – Bruno
    Mar 27 at 8:43












  • @Bruno see my edit?

    – U10-Forward
    Mar 27 at 8:45






  • 1





    @U9-Forward Yes sir, thanks

    – Bruno
    Mar 27 at 8:50













1












1








1








I'm trying to read and write a file with python file system but I'm having some problems. I believe that the reading/opening function is correct but the writing one is giving me a hard time.



I'm doing it inside a function that inverts a dictionary and I want it to read the dictionary from a text file instead of doing it inside the code, here's how I called it(not beautifully but works):



d = fin = open('dict.txt')


However, when it comes to writing the inverted dictionary to a file I'm failing miserably. The function call that prints the inverted dict is invert_dict(d) so I thought that I should try to write it like this:



invert_dict(d) = fout = open('output.txt', 'w')


Which is clearly wrong but that's what I got from reading a book. Here's my raw invert dictionary function :



def invert_dict(d):
print(' the dictionary is n' , d)
inverse = dict()
for key in d:
val = d[key]
for i in val:
if i not in inverse:
inverse[i] = [key]
else:
inverse[i].append(key)
return inverse
d='vowels':['a','e','i','o','u'], 'letters':['a','b','c','d']
print(invert_dict(d))


How should I improve my code? Thanks in advance.










share|improve this question
















I'm trying to read and write a file with python file system but I'm having some problems. I believe that the reading/opening function is correct but the writing one is giving me a hard time.



I'm doing it inside a function that inverts a dictionary and I want it to read the dictionary from a text file instead of doing it inside the code, here's how I called it(not beautifully but works):



d = fin = open('dict.txt')


However, when it comes to writing the inverted dictionary to a file I'm failing miserably. The function call that prints the inverted dict is invert_dict(d) so I thought that I should try to write it like this:



invert_dict(d) = fout = open('output.txt', 'w')


Which is clearly wrong but that's what I got from reading a book. Here's my raw invert dictionary function :



def invert_dict(d):
print(' the dictionary is n' , d)
inverse = dict()
for key in d:
val = d[key]
for i in val:
if i not in inverse:
inverse[i] = [key]
else:
inverse[i].append(key)
return inverse
d='vowels':['a','e','i','o','u'], 'letters':['a','b','c','d']
print(invert_dict(d))


How should I improve my code? Thanks in advance.







python python-3.x






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 27 at 8:47









martineau

74.5k11 gold badges101 silver badges193 bronze badges




74.5k11 gold badges101 silver badges193 bronze badges










asked Mar 27 at 8:31









BrunoBruno

223 bronze badges




223 bronze badges










  • 1





    if you want it to be properly, first use 'with open' construct (pythonforbeginners.com/files/…); also try to separate functionality - avoid creating superclass or supermethod in this case that does everything

    – Drako
    Mar 27 at 8:36











  • @Drako Sweet, so instead of using the ugly d = fin = open('dict.txt') I can use with open(“dict.txt”) as file:? Appreciate it! Regarding writing my output in a text file, thoughts? :)

    – Bruno
    Mar 27 at 8:43












  • @Bruno see my edit?

    – U10-Forward
    Mar 27 at 8:45






  • 1





    @U9-Forward Yes sir, thanks

    – Bruno
    Mar 27 at 8:50












  • 1





    if you want it to be properly, first use 'with open' construct (pythonforbeginners.com/files/…); also try to separate functionality - avoid creating superclass or supermethod in this case that does everything

    – Drako
    Mar 27 at 8:36











  • @Drako Sweet, so instead of using the ugly d = fin = open('dict.txt') I can use with open(“dict.txt”) as file:? Appreciate it! Regarding writing my output in a text file, thoughts? :)

    – Bruno
    Mar 27 at 8:43












  • @Bruno see my edit?

    – U10-Forward
    Mar 27 at 8:45






  • 1





    @U9-Forward Yes sir, thanks

    – Bruno
    Mar 27 at 8:50







1




1





if you want it to be properly, first use 'with open' construct (pythonforbeginners.com/files/…); also try to separate functionality - avoid creating superclass or supermethod in this case that does everything

– Drako
Mar 27 at 8:36





if you want it to be properly, first use 'with open' construct (pythonforbeginners.com/files/…); also try to separate functionality - avoid creating superclass or supermethod in this case that does everything

– Drako
Mar 27 at 8:36













@Drako Sweet, so instead of using the ugly d = fin = open('dict.txt') I can use with open(“dict.txt”) as file:? Appreciate it! Regarding writing my output in a text file, thoughts? :)

– Bruno
Mar 27 at 8:43






@Drako Sweet, so instead of using the ugly d = fin = open('dict.txt') I can use with open(“dict.txt”) as file:? Appreciate it! Regarding writing my output in a text file, thoughts? :)

– Bruno
Mar 27 at 8:43














@Bruno see my edit?

– U10-Forward
Mar 27 at 8:45





@Bruno see my edit?

– U10-Forward
Mar 27 at 8:45




1




1





@U9-Forward Yes sir, thanks

– Bruno
Mar 27 at 8:50





@U9-Forward Yes sir, thanks

– Bruno
Mar 27 at 8:50












1 Answer
1






active

oldest

votes


















1














Your code is pretty good, just using items to loop is better, and also setdefault is easier:



def invert_dict(d):
print(' the dictionary is n' , d)
inverse =
for k,v in d.items():
for i in v:
inverse.setdefault(i,[]).append(k)
return inverse


edit:



Misunderstood before, so you should use:



import json
d = fin = json.loads(open('dict.txt'))
with open('output.txt', 'w') as fout:
fout.write(invert_dict(d))





share|improve this answer






















  • 1





    Thanks! Regarding writing the inverted dictionary though, thoughts? :)

    – Bruno
    Mar 27 at 8:36






  • 1





    @Bruno I think this is the best as it gets :-) remember to accept and up-vote if it is good :-)

    – U10-Forward
    Mar 27 at 8:37






  • 1





    Again, appreciate your comment regarding this function, it took me a while to do it! However, maybe I didn't make myself clear, my issue is not with this function per se. I wanna change it through fin and fout function, which is the subject that I'm studying at the moment

    – Bruno
    Mar 27 at 8:40






  • 1





    @Bruno Edited my answer

    – U10-Forward
    Mar 27 at 8:42






  • 1





    Now I got it, thanks! So every time that I'm exchanging data I should import json and then carry on from there. Appreciate a lot your time, now I can carry on with my studies, thank you very much!

    – Bruno
    Mar 27 at 8:49










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55372743%2fhow-to-write-output-with-fout-function-in-properly%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














Your code is pretty good, just using items to loop is better, and also setdefault is easier:



def invert_dict(d):
print(' the dictionary is n' , d)
inverse =
for k,v in d.items():
for i in v:
inverse.setdefault(i,[]).append(k)
return inverse


edit:



Misunderstood before, so you should use:



import json
d = fin = json.loads(open('dict.txt'))
with open('output.txt', 'w') as fout:
fout.write(invert_dict(d))





share|improve this answer






















  • 1





    Thanks! Regarding writing the inverted dictionary though, thoughts? :)

    – Bruno
    Mar 27 at 8:36






  • 1





    @Bruno I think this is the best as it gets :-) remember to accept and up-vote if it is good :-)

    – U10-Forward
    Mar 27 at 8:37






  • 1





    Again, appreciate your comment regarding this function, it took me a while to do it! However, maybe I didn't make myself clear, my issue is not with this function per se. I wanna change it through fin and fout function, which is the subject that I'm studying at the moment

    – Bruno
    Mar 27 at 8:40






  • 1





    @Bruno Edited my answer

    – U10-Forward
    Mar 27 at 8:42






  • 1





    Now I got it, thanks! So every time that I'm exchanging data I should import json and then carry on from there. Appreciate a lot your time, now I can carry on with my studies, thank you very much!

    – Bruno
    Mar 27 at 8:49















1














Your code is pretty good, just using items to loop is better, and also setdefault is easier:



def invert_dict(d):
print(' the dictionary is n' , d)
inverse =
for k,v in d.items():
for i in v:
inverse.setdefault(i,[]).append(k)
return inverse


edit:



Misunderstood before, so you should use:



import json
d = fin = json.loads(open('dict.txt'))
with open('output.txt', 'w') as fout:
fout.write(invert_dict(d))





share|improve this answer






















  • 1





    Thanks! Regarding writing the inverted dictionary though, thoughts? :)

    – Bruno
    Mar 27 at 8:36






  • 1





    @Bruno I think this is the best as it gets :-) remember to accept and up-vote if it is good :-)

    – U10-Forward
    Mar 27 at 8:37






  • 1





    Again, appreciate your comment regarding this function, it took me a while to do it! However, maybe I didn't make myself clear, my issue is not with this function per se. I wanna change it through fin and fout function, which is the subject that I'm studying at the moment

    – Bruno
    Mar 27 at 8:40






  • 1





    @Bruno Edited my answer

    – U10-Forward
    Mar 27 at 8:42






  • 1





    Now I got it, thanks! So every time that I'm exchanging data I should import json and then carry on from there. Appreciate a lot your time, now I can carry on with my studies, thank you very much!

    – Bruno
    Mar 27 at 8:49













1












1








1







Your code is pretty good, just using items to loop is better, and also setdefault is easier:



def invert_dict(d):
print(' the dictionary is n' , d)
inverse =
for k,v in d.items():
for i in v:
inverse.setdefault(i,[]).append(k)
return inverse


edit:



Misunderstood before, so you should use:



import json
d = fin = json.loads(open('dict.txt'))
with open('output.txt', 'w') as fout:
fout.write(invert_dict(d))





share|improve this answer















Your code is pretty good, just using items to loop is better, and also setdefault is easier:



def invert_dict(d):
print(' the dictionary is n' , d)
inverse =
for k,v in d.items():
for i in v:
inverse.setdefault(i,[]).append(k)
return inverse


edit:



Misunderstood before, so you should use:



import json
d = fin = json.loads(open('dict.txt'))
with open('output.txt', 'w') as fout:
fout.write(invert_dict(d))






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 27 at 8:42

























answered Mar 27 at 8:34









U10-ForwardU10-Forward

27.6k5 gold badges21 silver badges48 bronze badges




27.6k5 gold badges21 silver badges48 bronze badges










  • 1





    Thanks! Regarding writing the inverted dictionary though, thoughts? :)

    – Bruno
    Mar 27 at 8:36






  • 1





    @Bruno I think this is the best as it gets :-) remember to accept and up-vote if it is good :-)

    – U10-Forward
    Mar 27 at 8:37






  • 1





    Again, appreciate your comment regarding this function, it took me a while to do it! However, maybe I didn't make myself clear, my issue is not with this function per se. I wanna change it through fin and fout function, which is the subject that I'm studying at the moment

    – Bruno
    Mar 27 at 8:40






  • 1





    @Bruno Edited my answer

    – U10-Forward
    Mar 27 at 8:42






  • 1





    Now I got it, thanks! So every time that I'm exchanging data I should import json and then carry on from there. Appreciate a lot your time, now I can carry on with my studies, thank you very much!

    – Bruno
    Mar 27 at 8:49












  • 1





    Thanks! Regarding writing the inverted dictionary though, thoughts? :)

    – Bruno
    Mar 27 at 8:36






  • 1





    @Bruno I think this is the best as it gets :-) remember to accept and up-vote if it is good :-)

    – U10-Forward
    Mar 27 at 8:37






  • 1





    Again, appreciate your comment regarding this function, it took me a while to do it! However, maybe I didn't make myself clear, my issue is not with this function per se. I wanna change it through fin and fout function, which is the subject that I'm studying at the moment

    – Bruno
    Mar 27 at 8:40






  • 1





    @Bruno Edited my answer

    – U10-Forward
    Mar 27 at 8:42






  • 1





    Now I got it, thanks! So every time that I'm exchanging data I should import json and then carry on from there. Appreciate a lot your time, now I can carry on with my studies, thank you very much!

    – Bruno
    Mar 27 at 8:49







1




1





Thanks! Regarding writing the inverted dictionary though, thoughts? :)

– Bruno
Mar 27 at 8:36





Thanks! Regarding writing the inverted dictionary though, thoughts? :)

– Bruno
Mar 27 at 8:36




1




1





@Bruno I think this is the best as it gets :-) remember to accept and up-vote if it is good :-)

– U10-Forward
Mar 27 at 8:37





@Bruno I think this is the best as it gets :-) remember to accept and up-vote if it is good :-)

– U10-Forward
Mar 27 at 8:37




1




1





Again, appreciate your comment regarding this function, it took me a while to do it! However, maybe I didn't make myself clear, my issue is not with this function per se. I wanna change it through fin and fout function, which is the subject that I'm studying at the moment

– Bruno
Mar 27 at 8:40





Again, appreciate your comment regarding this function, it took me a while to do it! However, maybe I didn't make myself clear, my issue is not with this function per se. I wanna change it through fin and fout function, which is the subject that I'm studying at the moment

– Bruno
Mar 27 at 8:40




1




1





@Bruno Edited my answer

– U10-Forward
Mar 27 at 8:42





@Bruno Edited my answer

– U10-Forward
Mar 27 at 8:42




1




1





Now I got it, thanks! So every time that I'm exchanging data I should import json and then carry on from there. Appreciate a lot your time, now I can carry on with my studies, thank you very much!

– Bruno
Mar 27 at 8:49





Now I got it, thanks! So every time that I'm exchanging data I should import json and then carry on from there. Appreciate a lot your time, now I can carry on with my studies, thank you very much!

– Bruno
Mar 27 at 8:49








Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55372743%2fhow-to-write-output-with-fout-function-in-properly%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현