如何使用列表中的数字作为Python词典的键?

如何使用列表中的数字作为Python词典的键?,python,python-2.7,python-3.x,dictionary,Python,Python 2.7,Python 3.x,Dictionary,我的文本文件是一个巨大的数据列表(大体上说,我无法手动格式化),仅由数字组成,格式如下: 1 5555 6666 2 5555 6666 1 7755 6666 3 8888 6666 我想使用前两列作为键,剩余的第三列作为它们的值 这是我的密码: import string def load (filename): with open ('filename', 'r'): dict = {} for line in file.readline(

我的文本文件是一个巨大的数据列表(大体上说,我无法手动格式化),仅由数字组成,格式如下:

 1 5555 6666
 2 5555 6666
 1 7755 6666
 3 8888 6666
我想使用前两列作为键,剩余的第三列作为它们的值

这是我的密码:

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
但是我的代码失败了

我想要的输出是:

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

有可能实现我的输出吗?我走对了吗?如果没有,我哪里出了问题,我如何修复它


谢谢

您可以使用csv模块读取内容,按传递的任何分隔符拆分元素,然后解包并使用元组中的前两个元素作为键,最后一个元素作为值:

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'}
如果要对数据进行排序,请使用OrderedICT:

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)
如果有机会重复这些键,则需要将值存储在列表或某个容器中:

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)
您自己的代码有多个错误:

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
然后调用传递文件名的函数:

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

您不应该重新定义内置类型
dict
。您应该编写正确的python代码:

def load(filename):
     with open('filename', 'r') as inp:
         result = {}
         for line in inp:
             key, site, value = line.strip().split('\t')
             result[key,site] = value
         return result

键必须是不可变的,而列表不是。改用元组,元组是不可变的。我一直收到错误“ValueError:太多的值无法解包(预期为3)”,这是否意味着这是不可能的?因为就像我说的,我的文本文件很大@PadraicCunningham@ShaunnaWilliams. 有一些可能性。你试了哪种代码?我试了你建议的第一种@PadraicCunningham@ShaunnaWilliams. 您的文件是如何分隔的?只是最后一个代码,这样我们就可以排除一些问题如果我的文件是以制表符分隔的,您确定这就是问题所在吗?我还是搞不懂@帕德雷坎宁厄姆