2016-12-05 9 views
1

は、次のように辞書にこれらのファイルを作るために私のコードがある2つのテキストファイルを辞書に入れるにはどうすればいいですか?例えば

2 
5 
7 

とtest_values.txt

ace 
ventura 
pet detective 

test_keys.txt、私は2つのテキストファイルを持っていると言います。私は私が私の結果の数字の前に\ nおよびスペースを取り除くことができますどのように

[(' 2\n', 'ace\n'), (' 5\n', 'ventura\n'), ('7', 'pet detective')] 

を取得するには

with open('test_keys.txt') as file1: 
    keys = file1.readlines() 
with open('test_values.txt') as file2: 
    values = file2.readlines() 
print(sorted(dict(zip(keys,values)).items())) 

?私はfile1.readlines()の後に.replace( '\ n'、 '')を試してみましたが、 'list'オブジェクトに 'replace'という属性がありません。助言がありますか?

+1

'keys = map(str.strip、file1.readlines())'? – jonrsharpe

+0

ありがとうございます – ORM

+1

'dict(zip(keys、values))。items()' - 'dict(...)。items()'の部分全体がなぜですか?それは冗長なようだ。 – user2357112

答えて

2

使用リスト番号にキーを変換した値を取り除くための読解:

keys = [int(key) for key in keys] 
values = [value.strip() for value in values] 

次に、あなたのコードに従ってください。

関連する問題