0

how do I build a for loop in order to print all float values in this nested dictionary, for any user?

   plist = {'user1': {u'Fake Plastic Trees': 1.0, u'The Numbers': 1.0, u'Videotape': 1.0}}

desired output = [1.0, 1.0, 1.0]

8-Bit Borges
  • 9,643
  • 29
  • 101
  • 198

2 Answers2

0

There's a dict.values() method that does exactly what you want.

a_dict = {'user1': {u'Fake Plastic Trees': 1.0, u'The Numbers': 1.0, u'Videotape': 1.0}}
first_key = list(a_dict.keys())[0]
values = a_dict[first_key].values()
print(list(values))

Output

[1.0, 1.0, 1.0]

Edit: And if you want to return one flattened list of all values for all keys as mentioned in the comments on the question, you can do this:

a_dict = {
    'user1': {u'Fake Plastic Trees': 1.0, u'The Numbers': 2.0, u'Videotape': 3.0},
    'user2': {u'Foo': 4.0, u'Bar': 5.0},
}
values = []
for k in a_dict.keys():
    for v in a_dict[k].values():
        values.append(v)
print(values)

Output

[4.0, 5.0, 3.0, 1.0, 2.0]
Taylor D. Edmiston
  • 12,088
  • 6
  • 56
  • 76
  • If something is incorrect about this answer with respect to your question, feel free to add a comment so it can be clarified. – Taylor D. Edmiston Nov 10 '16 at 17:57
  • Im sorry, I haven't downvoted it. but I've edited the question so it must not depend on a specific `string` as the outer `key` – 8-Bit Borges Nov 10 '16 at 17:59
  • @data_garden I've updated the answer to pull from the first key in the dictionary per the updated question. Note that this assumes there is only one key in the dictionary, which I believe is the case from reading your comments on the question. – Taylor D. Edmiston Nov 10 '16 at 18:04
0

Use dict.values() to get your desired behavior.

   >>> plist = {'playlist': {u'Fake Plastic Trees': 1.0, u'The Numbers': 1.0, u'Videotape': 1.0}}
    >>> list(plist['playlist'].values())
    [1.0, 1.0, 1.0]
    >>> 
Christian Dean
  • 22,138
  • 7
  • 54
  • 87