Howardb1990
Howardb1990

Reputation: 47

Adding a single list into a dictionary,

I am hoping someone can help me here. I am having some serious trouble adding a single list, from a text file into a dictionary. the list in the text file appears as:

20

Gunsmoke

30

The Simpsons

10

Will & Grace

14

Dallas

20

Law & Order

12

Murder, She Wrote

What I need is for each entry, one line at a time, to become the key and then value. For example it should look like {20:Gunsmoke, etc...}

I have to use the file.readlines() method according to my instructor. currently my code looks like this:

# Get the user input
inp = input()

# creating file object.
open = open(inp)

# read the file into seperate lines.
mylist = open.readlines()

# put the contents into a dictionary.
mydict = dict.fromkeys(mylist)

print(mydict) 

The out put looks like this:

file1.txt {'20\n': None, 'Gunsmoke\n': None, '30\n': None, 'The Simpsons\n': None, '10\n': None, 'Will & Grace\n': None, '14\n': None, 'Dallas\n': None, 'Law & Order\n': None, '12\n': None, 'Murder, She Wrote\n': None}

Process finished with exit code 0

There is more to this problem, but I am not here for someone to do my homework, I just cant figure out how to add this in properly. I have to be missing something and I am betting its simple. Thank you for your time.

Upvotes: 1

Views: 108

Answers (2)

001
001

Reputation: 13533

First, you can read the files without newlines using read().splitlines(). Then split the list into 2 lists containing every other word. Then zip those 2 lists together and create a dictionary from that:

inp = input()
with open(inp, 'r') as f:
    mylist = f.read().splitlines()
    mydict = dict(zip(mylist[::2], mylist[1::2]))

Note also: using with to automatically close the file when done.

Upvotes: 0

Chance
Chance

Reputation: 488

# Get the user input
inp = input()

# creating file object.
f = open(inp)

# read the file into seperate lines.
mylist = f.readlines()

# determine the total number of key/value pairs
total_items = len(mylist)//2

# put the contents into a dictionary.
# note: strip() takes off the \n characters
mydict = {mylist[i*2].strip(): mylist[i*2+1].strip() for i in range(0,total_items)}

print(mydict) 

Upvotes: 1

Related Questions