2015-10-08 18 views
0

我有一個問題,從包含其他幾個字典的字典中獲取某些值。它看起來像這樣:如何從1個字典中的幾個字典中檢索某個鍵的值?

dictionary = { 
    '1532': {'text': 'Hello World, nice day huh?', 
      'user': 'some_name', 
      'word_list': ['Hello', 'World', 'nice', 'day', 'huh']}, 
    '4952': {'text': "It's a beautiful day", 
      'user': 'some_name', 
      'word_list': ["It's", 'a', 'beautiful', 'day']}, 
    '7125': {'text': 'I have a problem', 
      'user': 'some_name', 
      'word_list': ['I', 'have', 'a', 'problem']}} 

我想要做的是遍歷字典,並在每次迭代只檢索「WORD_LIST」的值。

回答

0

只是迭代的dictionary那麼值:

for sub in dictionary.values(): 
    print(sub['word_list']) 

如果這是Python 2中,考慮使用dictionary.itervalues()讓你不用建立了循環一個新的列表對象。

這將產生:

>>> for sub in dictionary.values(): 
...  print(sub['word_list']) 
... 
["It's", 'a', 'beautiful', 'day'] 
['I', 'have', 'a', 'problem'] 
['Hello', 'World', 'nice', 'day', 'huh'] 

當然你也可以嵌套循環的;您可以進一步遍歷單詞列表:

for sub in dictionary.values(): 
    for word in sub['word_list']: 
     print(word) 
+0

謝謝你的幫助! – PeetZ

1

這裏是一個非常基本的方法:

for x in dictionary.values(): 
    print x["word_list"] 
+0

謝謝!這工作完美。 – PeetZ

0

使用pandas另一種方法:

import pandas as pd 

pd.DataFrame.from_dict(dictionary, orient='index').word_list.tolist() 

Out[407]: 
[['Hello', 'World', 'nice', 'day', 'huh'], 
["It's", 'a', 'beautiful', 'day'], 
['I', 'have', 'a', 'problem']] 

如果你想有詞語單個列表:

from itertools import chain 
import pandas as pd 

list(chain(*pd.DataFrame.from_dict(dictionary, orient='index').word_list)) 

Out[410]: 
['Hello', 
'World', 
'nice', 
'day', 
'huh', 
"It's", 
'a', 
'beautiful', 
'day', 
'I', 
'have', 
'a', 
'problem'] 
相關問題