2016-01-24 175 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

谢谢。如果我想像列中一样垂直输出它们,只输入条目而没有附加任何条目 –