2016-07-20 65 views
-2

我有一個返回字典(details_dict)並希望在另一個函數(內容)中打印此字典的函數(項目)。在函數中返回一個字典,然後在另一個函數中打印它的內容

details_dict的內容後for循環的是:

details_dict = { 
'car' : 'fast', 
'bike' : 'faster', 
'train' : 'slow' 
} 

這裏有兩個功能我實現了,但我不知道他們是對的。

def items(root): 
    for a in list: # example for loop, not important but details_dict is created here 
     details_dict = ['name' : 'state'] 
    return details_dict 

def contents(root): 
    for name, state in details_dict.items(): 
     print ("%s is set to %s" % (name, state) 
+1

是details_dict已經創造出來的?如果是這樣,爲什麼它在項目函數中被重新創建(儘管是錯誤的)?什麼是項目功能在做什麼? – Samuel

+0

不,它是通過for循環在項目(根)中創建的,il編輯問題 – zubinp

+4

*我不確定它們是否正確。* - [嘗試看看](https://repl.it/CeJY/0)。它工作嗎?它做什麼而不是工作? – TessellatingHeckler

回答

0

有沒有在你的打印語句和可能的縮進問題,缺少的括號。下面是你在做什麼修改後的版本,忽略的字典是如何構建的細節:

def buildItems(): 
    return { 
     'car': 'fast', 
     'bike': 'faster', 
     'train': 'slow' 
    } 

def contents(): 
    details_dict = buildItems() 
    for name, state in details_dict.items(): 
     print ("%s is set to %s" % (name, state)) 

contents() 

輸出:

car is set to fast 
train is set to slow 
bike is set to faster 

如果這是你想要它做什麼,它的工作原理。您可以在contents()函數內成功打印在另一個函數中創建的字典。

+0

請注意,在Python中,字典不保留順序。如果您需要維護訂單,請嘗試[OrderedDict](https://pymotw.com/2/collections/ordereddict.html) – voodoodrul

0

不知道你的數據結構,我做了一個最好的猜測。

list_a = ['car', 'bike', 'train'] 
list_b = ['fast', 'faster', 'slow'] 

def items (one, two): 
    the_dict = {} 
    for (i,j) in zip(one, two): 
     the_dict[i] = j 
    return the_dict 

def contents(a_dict): 
    for key in a_dict: 
     print 'The key ' +key+ ' is assigned to '+a_dict[key] 

details_dict = items(list_a, list_b) 

contents(details_dict) 

,輸出:

The key car is assigned to fast 
The key train is assigned to slow 
The key bike is assigned to faster 
相關問題