2016-01-24 227 views
0

我在想:如何從函數中的字典中單獨打印鍵或值?Python:單獨打印字典鍵和值

例.txt文件

00000000;Pikachu Muchacho;region1 
11111111;SoSo good;region2 
22222222;Marshaw williams;region3 
33333333;larry Mikal Carter;region3 

代碼

test_file = open("test.txt", "r") 
customer = {} 
def dictionary(): 
    for line in test_file: 
     entries = line.split(";") 
     key = entries[0] 
     values = entries[1] 
     customer[key] = values 

def test(): 
    print(customer) 
    print(customer[key]) 

def main(): 
    dictionary() 
    test() 

main() 
+0

customer.keys()和customer.values()給你所有的鍵和所有的值 – jamesRH

+0

我不是downvoting,但這是我真誠的建議,你在提出這樣的問題之前做更多的努力。 – Pukki

+0

我確實付出了努力。這就是爲什麼我問,因爲我嘗試了幾種不同的方法,我沒有弄明白。在給你的意見之前給它一點想法。我對語言和編碼一般都不熟悉。 –

回答

0

由於@jamesRH評論,你可以使用customer.keys()customer.values()

test_file = open("test.txt", "r") 
customer = {} 
def dictionary(): 
    for line in test_file: 
     entries = line.split(";") 
     key = entries[0] 
     values = entries[1] 
     customer[key] = values 

def test(): 
    # Print all the keys in customer 
    print(customer.keys()) 

    # Print all the values in customer 
    print(customer.values()) 

def main(): 
    dictionary() 
    test() 

main() 

這使輸出:

['00000000', '22222222', '33333333', '11111111'] 
['Pikachu Muchacho', 'Marshaw williams', 'larry Mikal Carter', 'SoSo good'] 

你原來的代碼會導致一個錯誤,因爲key不是test()範圍之內。

+0

謝謝。如果我想像列中一樣垂直輸出它們,只輸入條目而沒有附加任何條目 –