How do I use numbers in a list as keys for my dictionary in Python?

Jim Jones

My text file is a large list of data (by large meaning I can't format it by hand) consisting of only numbers and is formatted like this:

 1 5555 6666
 2 5555 6666
 1 7755 6666
 3 8888 6666

I would like to use the first two columns as my keys and the third remaining column as their value.

Here is my code:

import string
def load (filename):
    with open ('filename', 'r'):
        dict = {}
        for line in file.readline():
            key, site, value = dict([line.strip().split('\t')for line in file
            dict[key[0]]+[site[1]]= value[2]
        return dict

However my code fails.

My desired output is this:

{('1', '5555'): '6666', ('2', '5555'): '6666', ('1', '7755'): '6666', ('3', '8888'): '6666'}

Is it possible to achieve my output? Am I on the right track? If not, where did I go wrong and how can I fix it?

Thank you

Padraic Cunningham

You can use the csv module to read the content splitting the elements by whatever delimiter you pass then unpack and use the first two elements in a tuple as the key and the last as the value:

import csv

with open("in.csv") as f:
    d = {}
    r = csv.reader(f, delimiter=" ") # pass whatever your delimiter is
    for row in r: # first row  1 5555 6666 -> ["1", "5555", "6666"]
        a, b, v = row # a,b,c = "1", "5555", "6666"
        d[(a, b)] = v # create a tuple from the first two elements of the row
print(d)
{('3', '8888'): '6666', ('1', '5555'): '6666', ('1', '7755'): '6666', ('2', '5555'): '6666'}

If you want the data ordered use an OrderedDict:

import csv
from collections import OrderedDict
with open("in.csv") as f:
    d = OrderedDict()
    r = csv.reader(f, delimiter=" ")
    for row in r:
        a, b, v = row
        d[(a, b)] = v
print(d)

If you had a chance the the keys could repeat then you would need to store the values in a list or some container:

import csv
from collections import OrderedDict
with open("in.csv") as f:
    d = OrderedDict()
    r = csv.reader(f, delimiter=" ")
    for row in r:
        a, b, v = row
        d.setdefault((a,b),[]).append(v)
print(d)

You own code has multiple mistakes:

def load(filename):
    with open(filename, 'r') as f: # as f and pass variable filename not a string
        d = {} # don't shadow the python dict 
        for line in f: # iterate over the file object
            key, site, value = line.split() # unpack
            d[(key, site)] = value # already unpacked so just use the variables
        return d

Then call your function passing the filename:

print(load("in.csv"))
{('1', '5555'): '6666', ('3', '8888'): '6666', ('2', '5555'): '6666', ('1', '7755'): '66`66'}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I use dictionary to replace numbers in a list?

How do I return dictionary keys as a list in Python?

How do I get the list of keys in a Dictionary?

How do I access the "yes" and "no" keys in my dictionary and put their values in to a list?

How do I change the names of my keys in a dictionary?

How do I initialize a dictionary with a list of keys and values as empty sets in python3.6?

How do I create a dictionary in Python when a user inputs a list of words that are to be the keys and values?

How do I convert list into dictionary in Python?

Python: How can I turn a list of tuples into dictionary keys?

How do I sort a python dictionary values and rearrange keys?

How do I remove certain keys from a nested dictionary in Python?

How do I get keys that correspond to values in Python dictionary?

How do I configure multiple dictionary keys in a yaml file in Python?

How do I use python or pandas to filter a DataFrame based on a column that consists of a list of dictionary?

In Python how do I use a for loop, to create nested list from dictionary?

How do I use a list or set as keys in file renaming

How do I exchange keys with values in a dictionary?

In python, with tkinter, how do I create shortcut keys for my widgets?

How to return dictionary keys as a list in Python?

How can I square the list of numbers in a dictionary?

Python Pandas: How to use dictionary on a column which contains a list of keys to create another column of a list of values

(python) How do I obtain specific entries from a dictionary (using keys) as I do with an array?

How would I adjust my Python code for a nested .JSON tree (Python dictionary) to include multiple keys?

How do i create array/list keys in python?

How do I get my numbers in python to show up with $?

How do I add numbers and spaces to my typing function in Python?

How do I find the last item of the list in a Python dictionary?

Python: How do I remove elements from a dictionary and return it as a list?

How do I convert a list to dictionary with specific format in python?