2017-06-05 93 views
0

我不能两个列表合并成一个dictionary.I尝试了以下内容:不能合并两个列表成为一个字典

Map two lists into a dictionary in Python

我尝试了所有的解决方案,我仍然得到一个空的字典

from sklearn.feature_extraction import DictVectorizer 
from itertools import izip 
import itertools 

text_file = open("/home/vesko_/evnt_classification/bag_of_words", "r") 
text_fiel2 = open("/home/vesko_/evnt_classification/sdas", "r") 
lines = text_file.read().split('\n') 
words = text_fiel2.read().split('\n') 


diction = dict(itertools.izip(words,lines)) 
new_dict = {k: v for k, v in zip(words, lines)} 
print new_dict 

我得到以下:

{ '单词': ''} [ '字=']

这两个列表不是空的。

我使用python2.7

编辑:

从两个列表输出(我只显示几个,因为它是用11K特征向量)

//lines 
['change', 'I/O', 'fcnet2', 'ifconfig',.... 
//words 
['word', 'word', 'word', ..... 

编辑:

现在至少我有一些输出@DamianLattenero

{'word\n': 'XXAMSDB35:XXAMSDB35_NGCEAC_DAT_L_Drivei\n'} 
['word\n=XXAMSDB35:XXAMSDB35_NGCEAC_DAT_L_Drivei\n'] 
+0

打印出'lines'和'words'是为了确保工作正常 – MrJLP

+0

您还需要额外的导入。在这个例子中'DictVectorizer'没有使用,可能'itertools'不需要,如下面的回答所示 – MrJLP

+0

@MrJLP这是正确的,问题应该在数据加载中 –

回答

0

我尝试了这个并为我工作,我创建了两个文件,添加了数字1到4,字母a到d,并且代码创建了字典好了,我不需要导入itertools,实际上还有一个额外的不需要线:

lines = [1,2,3,4] 
words = ["a","b","c","d"] 


diction = dict(zip(words,lines)) 
# new_dict = {k: v for k, v in zip(words, lines)} 
print(diction) 

{ 'A':1, 'b':2, 'C':3, 'd':4}

是否奏效的,而不是另一方面,您必须在加载列表时遇到问题,请尝试像这样加载:

def create_list_from_file(file): 
    with open(file, "r") as ins: 
    my_list = [] 
    for line in ins: 
     my_list.append(line) 
    return my_list 

lines = create_list_from_file("/home/vesko_/evnt_classification/bag_of_words") 
words = create_list_from_file("/home/vesko_/evnt_classification/sdas") 

diction = dict(zip(words,lines)) 
# new_dict = {k: v for k, v in zip(words, lines)} 
print(diction) 

观察: 如果files.txt看起来是这样的:

1 
2 
3 
4 

a 
b 
c 
d 

结果将有钥匙在字典中,每行一个:

{'a\n': '1\n', 'b\n': '2\n', 'c\n': '3\n', 'd': '4'} 

但是,如果你的文件看起来像:

1 2 3 4 

a b c d 

结果将是{'a b c d': '1 2 3 4'},只有一个值

+1

也许问题来自阅读文件 – MrJLP

+0

由于一些奇怪的原因,这在我的情况下@DamianLattenero –

+0

@VeselinIvanov不起作用即使这两个测试列表?因为如果这些列表适合你并且执行这项工作,问题是当你从文件中加载想要的列表时......你是否尝试过使用列表中的这些值? –

1

我想了很多混乱的根源是代码的例子这是不相关的。

试试这个:

text_file = open("/home/vesko_/evnt_classification/bag_of_words", "r") 
text_fiel2 = open("/home/vesko_/evnt_classification/sdas", "r") 
lines = text_file.read().split('\n') 
words = text_fiel2.read().split('\n') 

# to remove any extra newline or whitespace from what was read in 
map(lambda line: line.rstrip(), lines) 
map(lambda word: word.rstrip(), words) 

new_dict = dict(zip(words,lines)) 
print new_dict 

的Python内建zip()收益从每个参数元组的迭代。将这个元组迭代到dict()对象构造函数创建一个字典,其中words中的每个项目都是关键字,而lines中的项目是相应的值。

另请注意,如果words文件的项目数多于lines,那么将使用空值键。如果lines包含项目,则只有最后一项将添加None项。

+1

我同意,这应该工作,如果没有,路径或有什么问题。另外一个清晰 –

+0

我已经试过MrJLP也没有工作。 –

+0

发生了什么事?输出是什么? – MrJLP