Making a dictionary from each line in a file

converting text file to dictionary python
load text file into dictionary python
python write dictionary to file line by line
python read dictionary from file
python create dictionary from text file
how to format each dictionary item as a text string in the input file.
text to dictionary python
python read lines from file into dictionary

I am trying to make a dictionary from this file: with the key being the first word, and the values being all words afterwards.

andrew fred
judy andrew fred
george judy andrew
john george

This is the code I have:

follows_file = open("C:\\Users\\Desktop\\Python\\follows.txt")
followers = {}
for line in follows_file:   #==> [Judy Andrew Fred]
    users = line.split(' ')     #==> [Judy, andrew, Fred, ....]
    follower = users[0]     #==> [Judy]
    followed_by = users[1:] #==> [Andrew, Fred]

    for user in followed_by:
        # Add the 'follower to the list of followers user
        if user not in followers:
            followers[user] = []

When I print the follower and followed by variable, they are correct, but i'm having trouble adding them into the dictionary correctly; with this being the output

dict_items([('fred\n', ['andrew', 'judy']), ('andrew', ['judy']), ('judy' ['george']), ('andrew\n', ['george']), ('george', ['john'])])

My desired output would be

(Andrew[Fred])(Fred[])(judy[Andrew Fred])(George[Judy Fred])(john[george])

Any assistance is much appreciated!

Edited answer, improved thanks to the comments from @PM2Ring and @IljaEverilä.

Here is my original solution using a dictionary comprehension

followers = {line.split()[0]: line.split()[1:] for line in follows_file}

A more efficient alternative proposed by @IljaEverilä, which avoids calling split twice, is:

followers = {follower: followees for follower, *followees in map(str.split, follows_file)}


{'andrew': ['fred'],
 'fred': [],
 'george': ['judy', 'andrew'],
 'john': ['george'],
 'judy': ['andrew', 'fred']}

Note that both of the above solutions assume that your file contains no duplicate keys.

Don't forget to close your file afterwards:


Or better, just use a context manager, which handles the file closing for you:

with open('C:\\Users\\zacan\\Desktop\\Python\\follows.txt', 'r') as follows_file:
    followers = {follower: followees for follower, *followees in map(str.split, follows_file)}

How to create a Python dictionary from text file?, Assuming a following text file (dict.txt) is present1 aaa2 bbb3 cccFollowing Python code reads the file using open() function. Each line as string  Assuming a following text file (dict.txt) is present. 1 aaa. 2 bbb. 3 ccc. Following Python code reads the file using open() function. Each line as string is split at space character.

You can use collections.defaultdict() as a dictionary factory and just append the users following a person, e.g.:

import collections

followers = collections.defaultdict(list)  # use a dict factory to save some time on checks
with open("path/to/your_file", "r") as f:  # open the file for reading
    for line in f:  # read the file line by line
        users = line.split()  # split on any white space
        followers[users[0]] += users[1:]  # append the followers for the current user

Which will produce, for your data:

{'andrew': ['fred'],
 'fred': [],
 'judy': ['andrew', 'fred'],
 'george': ['judy', 'andrew'],
 'john': ['george']}

This will also allow you to have multiple lists appended to the user on a repeating record - otherwise you can just use a normal dict for followers and set them as followers[users[0]] = users[1:].

The data structure you've shown as your desired output is not valid Python, do you really want it presented that way? I mean, if you insist you can do it as:

print("".join("({}[{}])".format(k, " ".join(v)) for k, v in followers.items()))
# (andrew[fred])(fred[])(judy[andrew fred])(george[judy andrew])(john[george])

Dictionaries, If we print the dictionary again, we see a key-value pair with a colon between the key and in the string and we only have to make room for the letters that do appear. We will write a Python program to read through the lines of the file, break  Anyway this will always create new dictionary for each line. If you want to have same dictionary with all values, you need to either "collect" all key: value pairs and then convert them into dict at once, or create dictionary and update it for each line.

This is one solution using str.split and a try / except clause to capture instances where only a key exists.

Note io.StringIO lets us read from a string as if it were a file.

from io import StringIO
import csv

mystr = StringIO("""andrew fred
judy andrew fred
george judy andrew
john george""")

# replace mystr with open("C:\\Users\\zacan\\Desktop\\Python\\follows.txt")
with mystr as follows_file:
    d = {}
    for users in csv.reader(follows_file):
            key, *value = users[0].split()
        except ValueError:
            key, value = users[0], []

        d[key] = value


{'andrew': ['fred'],
 'fred': [],
 'george': ['judy', 'andrew'],
 'john': ['george'],
 'judy': ['andrew', 'fred']}

Files, Strings, and Dictionaries, How can we read the rainfall data in this file and make a plot of the values? The most straightforward solution is to read the file line by line, and for each line split​  each line in the text will have a username, first name, last name, age, gender and an e-mail address. The function will insert each person's information into a dictionary with their username as the key, and the value being a list of [last name, first name, e-mail, age, gender].

followers = dict()
with open('C:\\Users\\zacan\\Desktop\\Python\\follows.txt', 'r') as f:
    for line in f:
        users = line.split(' ')
        followers[users[0]] = [_ for _ in users[1:]]

this should work, didn't test it

How to write a dictionary to a file in Python, a Python dictionary to a file in the format you've described (as simple lines of text There is one another way, by making subclass of dictionary and overriding​  Format the document as a single column, one word per line, each line ending with a line break; hit the <Enter> key to place the line break. Save the file as Unicode with file extension .dic. Import (Add) your new custom dictionary to Word.

Python: convert a text file into a dictionary, Given the following data in a text file the task is to convert it into a Python dict commands = {} with open(filename) as fh: for line in fh: command, So instead of splitting on each space it splits on the first space only which  Dictionary keys must be unique. You have only one unique key in that file. You are in essence assigning different values to the same key, and only the last value is visible as the previous values are overwritten: >>> d = {} >>> d['asd'] = 209 >>> d['asd'] = 441 >>> d {'asd': 441} To store the largest value, use:

opening a text file and building a dictionary, each line in the text will have a username, first name, last name, age, gender and an e-mail address. The function will insert each person's  Counting word frequency and making a dictionary from it. function and use for line in file_descriptor: Make each new word a key into Dictionary with value 1.

Python: 4 ways to print items of a dictionary line by line – thispointer , Although it printed the contents of the dictionary, all the key-value pairs printed in a single line. If we have big dictionaries, then it can be hard for  Many times it is required to count the occurrence of each word in a text file. To achieve so, we make use of a dictionary object that stores the word as the key and its count as the corresponding value. We iterate through each word in the file and add it to the dictionary with count as 1.