PeetZ
PeetZ

Reputation: 89

How to retrieve values from a certain key from several dicts inside 1 dict?

I have a problem getting certain values from a dict that contains several other dicts. It looks like this:

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']}}

What I want to do is iterate over the dictionary and with each iteration only retrieve the value of 'word_list'.

Upvotes: 0

Views: 48

Answers (3)

Colonel Beauvel
Colonel Beauvel

Reputation: 31181

An alternative approach using 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']]

If you want to have the words in a single list:

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']

Upvotes: 0

unwind
unwind

Reputation: 400139

Here's a very basic approach:

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

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1125078

Just iterate over the values of dictionary then:

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

If this is Python 2, consider using dictionary.itervalues() so you don't build up a new list object for the loop.

This produces:

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

You can of course nest the looping; you can further loop over the word list:

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

Upvotes: 0

Related Questions