data_garden data_garden - 1 month ago 14
Python Question

Python - 'unicode' object has no attribute 'values'

I have this

dictionary
:

playlists = {
u'user1': {u'Make You Feel My Love': 1.0, u'I See Fire': 1.0, u'High And Dry': 1.0, u'Fake Plastic Trees': 1.0, u'One': 1.0, u'Goodbye My Lover': 1.0, u'No Surprises': 1.0},
u'user2': {u'Fake Plastic Trees': 1.0, u'High And Dry': 1.0, u'No Surprises': 1.0},
u'user3': {u'Codex': 1.0, u'No Surprises': 1.0, u'O': 1.0, u'Go It Alone': 1.0},
u'user4': {u'No Distance Left To Run': 1.0, u'Running Up That Hill': 1.0, u'Fake Plastic Trees': 1.0, u'The Numbers': 1.0, u'No Surprises': 1.0}, u'user5': {u'Wild Wood': 1.0, u'You Do Something To Me': 1.0, u'Reprise': 1.0}}


and I'm trying to fetch
float values
.

with:

print playlist.keys()[0]
print [p for p in playlist.values()[0]]


I succeed.

but if I try
[p.values() for p in playlist.values()]
, I get the following error:

AttributeError: 'unicode' object has no attribute 'values'


how do I get
values
?

Answer

Performing [p for p in playlists.values()] returns a list of dictionaries. So, you cannot use the values() method directly on it.

Instead, you must break individual dicts contained in the list of dictionaries on every iteration and then use it's built-in values() method as shown:

[d.values() for d in [p for p in playlists.values()]]
# [[1.0, 1.0, 1.0],
# [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
# [1.0, 1.0, 1.0],
# [1.0, 1.0, 1.0, 1.0],
# [1.0, 1.0, 1.0, 1.0, 1.0]]