2013-03-26 85 views
0

我有一個文本文件,其中包含一組餐廳的詳細信息。細節是特定餐廳的名稱,評級,價格和烹飪類型。文本文件的內容如下所示。從文本文件填充字典

George Porgie 
87% 
$$$ 
Canadian, Pub Food 

Queen St. Cafe 
82% 
$ 
Malaysian, Thai 

Dumpling R Us 
71% 
$ 
Chinese 

Mexican Grill 
85% 
$$ 
Mexican 

Deep Fried Everything 
52% 
$ 
Pub Food 

我想打造一個集字典下面給出:

Restaurant name to rating: 
# dict of {str : int} 
name_to_rating = {'George Porgie' : 87, 
'Queen St. Cafe' : 82, 
'Dumpling R Us' : 71, 
'Mexican Grill' : 85, 
'Deep Fried Everything' : 52} 

Price to list of restaurant names: 
# dict of {str : list of str } 
price_to_names = {'$' : ['Queen St. Cafe', 'Dumpling R Us', 'Deep Fried Everything'], 
'$$' : ['Mexican Grill'], 
'$$$' : ['George Porgie'], 
'$$$$' : [ ]} 

Cuisine to list of restaurant name: 
#dic of {str : list of str } 
cuisine_to_names = {'Canadian' : ['George Porgie'], 
'Pub Food' : ['George Porgie', 'Deep Fried Everything'], 
'Malaysian' : ['Queen St. Cafe'], 
'Thai' : ['Queen St. Cafe'], 
'Chinese' : ['Dumpling R Us'], 
'Mexican' : ['Mexican Grill']} 

什麼是Python中填充上述詞典的最佳方式?

+4

向我們展示你已經什麼試過。 – Blender 2013-03-26 04:55:18

+0

我只知道使用Python從文本文件逐行閱讀線 – 2013-03-26 05:06:14

+1

這是Coursera的作業。 – 2013-03-26 05:40:51

回答

1

初始化一些容器:

name_to_rating = {} 
price_to_names = collections.defaultdict(list) 
cuisine_to_names = collections.defaultdict(list) 

讀取您的文件到臨時字符串:

with open('/path/to/your/file.txt') as f: 
    spam = f.read().strip() 

假設結構是一致的(即,由雙換行符分隔4線的塊),迭代通過大塊和填充您的容器:

restraunts = [chunk.split('\n') for chunk in spam.split('\n\n')] 
for name, rating, price, cuisines in restraunts: 
    name_to_rating[name] = rating 
    # etc .. 
0

爲主要閱讀l空中接力,您可以用枚舉和模知道什麼是線路上的數據:

for lineNb, line in enumerate(data.splitlines()): 
    print lineNb, lineNb%4, line 

price_to_namescuisine_to_names dictionnaries,你可以使用一個defaultdict:

from collections import defaultdict 
price_to_names = defaultdict(list) 
+0

@ niroyb:我正在處理你的答案。非常感謝。會回來。 – 2013-03-26 05:21:59