2013-03-26 89 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