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