2015-12-21 45 views
-4
requestArr= { 
    'test1': { 
     "id_comments": "ABC", 
     "id_testname": "abc", 
    }, 
    'test2' : { 
     "id_comments": "DEF", 
     "id_testname": "def", 
    }, 
    'test3' : { 
     "id_comments": "GHI", 
     "id_testname": "ghi", 
    } 
} 

如何在python「For循環」中逐個添加值,例如:如何在python中循環迭代字典?

test1{id_comments & id_testname} 
# and so on 

e.g.-

for i in requestArr: 
    for j in requestArr[i]: 
     for k in requestArr[i][j]: 
      print k['id_comments'] 
      print k['id_testname'] 
      # query to database 

得到錯誤

指數必須是整數,而不是str的

我怎樣才能做到這一點?

+0

你能再解釋一下你想要什麼嗎?我不明白。你想定義值還是讀取它們? – tglaria

+0

'在requestArr.values()中打印元素:print elem' – Ingaz

+1

感謝CoryKramer用合適的字體進行編輯。 tglaria現在很好地看到這個問題。 –

回答

1

您可以在字典迭代items

for key, value in requestArr.items(): 
    print(key, value) 

輸出

test2 {'id_comments': 'DEF', 'id_testname': 'def'} 
test1 {'id_comments': 'ABC', 'id_testname': 'abc'} 
test3 {'id_comments': 'GHI', 'id_testname': 'ghi'} 
+0

會工作,但這是python3。還應該使用'viewitems()' –

+1

@ cricket_007這將在Python 3.x和Python 2.7中都有效。在這種情況下,它是不重要的,如果他們使用'item'或'viewitems' – CoryKramer

+0

嗨@Corykramer,我想實現這一點 - 對於我在requestArr: 對於requestArr [i]: 對於requestArr [i ] [j]: print k ['id_comments'] print k ['id_testname'] #query to database –

1

的Python 2.7

items()將返回元組的列表。

>>> requestArr.items() 
[('test1', {'id_comments': 'ABC', 'id_testname': 'abc'}), ('test3', {'id_comments': 'GHI', 'id_testname': 'ghi'}), ('test2', {'id_comments': 'DEF', 'id_testname': 'def'})] 

iteritems()將返回itemiterator對象。

>>> requestArr.iteritems() 
<dictionary-itemiterator object at 0xb6d3b734> 
>>> for k, v in requestArr.iteritems(): 
... print k, v 
... 
test1 {'id_comments': 'ABC', 'id_testname': 'abc'} 
test3 {'id_comments': 'GHI', 'id_testname': 'ghi'} 
test2 {'id_comments': 'DEF', 'id_testname': 'def'} 
>>> 

Python 3.x都有

一個Python 3中的變化是,項目()現在返回迭代器,和一個列表是從來沒有完全建立。 iteritems()方法也不見了,因爲items()現在可以像Python 2中的iteritems()一樣工作。