2016-05-17 26 views
1

我有一個txt文件,我想讀取字典中的值。從普通字典不同的是,每個key的值是值對,例如:如何從文件創建Python中的字典,其中的值是一個列表

tiger eat meat 
tiger eat people 
rabbit eat carrot 
people can walk 
trees has root 
people has hand 

我希望得到一本字典是,

tiger, {eat, meat}, {eat, people} 
rabbit, {eat, carrot} 
trees, {has, root} 
people, {can, walk}, {has, hand} 

我應該只是read linessplit(\n)到3項和將第一個存儲爲關鍵字,其餘兩個存儲爲值?或者有更好的方法來存儲這兩個值?

我的目標是,當我查詢老虎吃什麼時,我想得到答案meatpeople

+1

你能告訴你想實際的字典結構,而不是這個陌生的非Python的僞代碼? –

+0

您需要上傳迄今爲止所做的工作。更重要的是,你的數據結構沒有任何字典。這就是你想要的:'{'tiger':[{'eat':'meat'},{'eat':'people'}]}'? –

+0

@MosesKoledoye是〜 – flyingmouse

回答

3
import collections 

lines=[] 
with open('data1', 'r') as f: 
    lines=list(map(lambda line:line.strip(), f.readlines())) 

d, flag=collections.defaultdict(list), False 
for line in lines: 
    temp=list(map(lambda x:x.strip(), line.split())) 
    d[temp[0]].append(temp[1:]) 
print(d) 

這裏是輸出:

$ cat data1 
tiger eat meat 
tiger eat people 
rabbit eat carrot 
people can walk 
trees has root 
people has hand 
$ python3 a.py 
defaultdict(<class 'list'>, {'rabbit': [['eat', 'carrot']], 'trees': [['has', 'root']], 'tiger': [['eat', 'meat'], ['eat', 'people']], 'people': [['can', 'walk'], ['has', 'hand']]}) 

如果你想這樣的結構:

$ python3 a.py 
defaultdict(<class 'list'>, {'people': [{'can': 'walk'}, {'has': 'hand'}], 'tiger': [{'eat': 'meat'}, {'eat': 'people'}], 'trees': [{'has': 'root'}], 'rabbit': [{'eat': 'carrot'}]}) 

更換2號最後一行的腳本:

d[temp[0]].append({temp[1]:temp[2]}) 
0

一旦您已經閱讀從文件中的行,你可以爲此創建一個nested defaultdict

d = defaultdict(lambda: defaultdict(list)) 

for line in lines: 
    words = line.split() 
    d[words[0]][words[1]].append(words[2]) 

如果print(d),你會得到如下:

defaultdict(<function <lambda> at 0x7fa858444320>, {'tiger': defaultdict(<type 'list'>, {'eat': ['meat', 'people'], 'eats': []}), 'trees': defaultdict(<type 'list'>, {'has': ['root']}), 'rabbit': defaultdict(<type 'list'>, {'eat': ['carrot']}), 'people': defaultdict(<type 'list'>, {'has': ['hand'], 'can': ['walk']})}) 

而且,您可以訪問哪些虎吃如下:

>>> d['tiger']['eat'] 
['meat', 'people'] 

如果你想看到什麼都可以一people做到:

>>> d['people']['can'] 
['walk'] 
1

首先,你可以積累數據的基礎上,主題和動詞,這樣

data = {} 
with open("Input.txt") as fin: 
    for line in fin: 
     subject, verb, obj = line.strip().split() 
     data.setdefault(subject, {}).setdefault(verb, []).append(obj) 

現在,data看起來像這樣

我們基本上已經創建了嵌套字典的價值列表。

現在,它只是迭代和打印結果,以這樣的方式簡單的事情你喜歡

for subject in data: 
    print subject, 
    for verb in data[subject]: 
     for obj in data[subject][verb]: 
      print "{{{}, {}}}".format(verb, obj), 
    print 

輸出

tiger {eat, meat} {eat, people} 
trees {has, root} 
rabbit {eat, carrot} 
people {has, hand} {can, walk} 

注:如果原數據的順序很重要,那麼可以使用collections.OrderedDict而不是使用普通字典,就像此

from collections import OrderedDict 


data = OrderedDict() 
with open("Input.txt") as fin: 
    for line in fin: 
     subject, verb, obj = line.strip().split() 
     data.setdefault(subject, OrderedDict()).setdefault(verb, []).append(obj) 
1

創建字典的鍵是主體和其值是含有字典與動詞作爲鍵和對象值(見結果)的列表。

animal_attr = {} #Don't mind the name :) 
with open (filename,"r") as f: 
    for line in f: 
     items = line.split() 
     if items[0] not in animal_attr.keys(): 
      animal_attr[items[0]] = []    
     animal_attr[items[0]].append({items[1]: items[2]}) 

print(animal_attr) 
#{'tiger': [{'eat': 'meat'}, {'eat': 'people'}], 'trees': [{'has': 'root'}], 
# 'rabbit': [{'eat': 'carrot'}], 'people': [{'can': 'walk'}, {'has': 'hand'}]} 
0
import collections 

d=collections.defaultdict(list) 
with open('text.txt', 'r') as lines: 
    for line in lines: 
     temp=line.split() 
     d[temp[0]].append({temp[1]: temp[2]}) 
print(d) 

輸出:

defaultdict(<type 'list'>, {'tiger': [{'eat': 'meat'}, {'eat': 'people'}], 'trees': [{'has': 'root'}], 'rabbit': [{'eat': 'carrot'}], 'people': [{'can': 'walk'}, {'has': 'hand'}]}) 
相關問題