0

Is there an easier way of creating a dictionary on Python from a .txt file than this:

for y in open('bones.txt'):
    bones={','.join(y:'0')}

where bones.txt contains:

Ankylosaurus
Pachycephalosaurus
Ankylosaurus
Tyrannosaurus Rex
Ankylosaurus
Struthiomimus
Struthiomimus
Sumedh Junghare
  • 381
  • 2
  • 4
  • 21

3 Answers3

3
with open("bones.txt") as f:
    my_dict = dict.fromkeys(f, '0')

Thanks for the suggustions and I get this answer above.

  1. use dict instead of {}

  2. Don't use readlines. The file iterator works

to clean out line breaks, maybe we can use os.linesep

import os
with open("bones.txt") as f:
    my_dict = dict.fromkeys(map(lambda x: x.replace(os.linesep, ""), f), '0')
Henry
  • 176
  • 6
0

You can use a dict comprehension.

with open('bones.txt') as f:
    bones = { line: 0 for line in f.read().splitlines() }

str.splitlines does not include the newline character to the lines, so we don't have to strip it.

Sasha Tsukanov
  • 1,025
  • 9
  • 20
0

This method can also be modified to include values for keys without making it too complicated:

bones = {}
for y in open('bones.txt'):
   bones[y.strip('\n')] = '0'
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Darth_Sourav
  • 116
  • 7
  • 2
    Why convert something that is already a string into a string? – Mad Physicist Aug 22 '18 at 12:51
  • 1
    Why not use a with block when you really should? – Mad Physicist Aug 22 '18 at 12:52
  • I wanted to do it keeping Op's approach. and newline character is there to strip. for your point 1, I made the edit. Thanks. – Darth_Sourav Aug 22 '18 at 12:57
  • OP came here to learn. It's up to you to instruct him not to make the mistakes he's making. – Mad Physicist Aug 22 '18 at 13:02
  • Ideally you could include the `with`-based solution with a little comment after yours to your answer – Sasha Tsukanov Aug 22 '18 at 13:24
  • @SashaTsukanov The solution including `with` based solution provided by Henry yuan and Mad Physicist is more elegant. Personally I wanted to present a solution with the basic operations which gives the solution keeping Op's way of thought. – Darth_Sourav Aug 22 '18 at 15:24
  • @MadPhysicist can you please tell me what have you edited in my solution so I can keep that in mind for the future? – Darth_Sourav Aug 22 '18 at 15:27
  • 1
    When a vote sits for too long, you can't change it unless an edit is made to the post. I wanted to remove my downvote, so I made an edit that I considered to be harmless. If you want me to change the colon back to a period, I'd be more than happy to do it. – Mad Physicist Aug 22 '18 at 15:31
  • Wishing had the privilege to upvote your comment. and no, the colon is harmless. cheers. – Darth_Sourav Aug 22 '18 at 15:39