Friday, February 12, 2016

Reading file contents into a Python dictionary

Here's a simple example of how to populate a Python dictionary with the contents of a text file. This uses the first column as the key and the second as the value, appending duplicate entries to a list.
#!/usr/bin/python

my_dict = {}
my_dups = []

with open("my_file", "r") as ins:
    for line in ins:
        l=line.strip().split(" ")
        new_key = l[0]
        new_val = l[1]
        if new_key in my_dict:
            curr_val = my_dict[new_key]
            new_dup_entry = curr_val + " is duplicated at " + new_val
            my_dups.append(new_dup_entry)
        else: 
            my_dict[new_key] = new_val

for dup_entry in my_dups:
    print dup_entry
And here's an example output:
# cat my_file
a aaa
b bbb
a ccc

# ./example.py
aaa is duplicated at ccc

No comments:

Post a Comment