So I have a dictionary called 'useraccounts'. I manage to obtain all of the keys of the items in the dictionary that are in class 12 by doing:
found = ([k for k in useraccounts if useraccounts[k]['class'] == '12'])
The list returned is:
['bob', 'terry']
which is correct. Now is there anyway I could take these results as keys and then seperately use them to individually print relevant information from the dictionary. For example, get the program to print the results of:
useraccounts[THE_KEYS_FOUND_IN_THE_LIST]['totalscore']
Any help is greatly appreciated.
Thanks in advance.
asked Feb 9, 2014 at 20:27
MrPython
2681 gold badge4 silver badges15 bronze badges
3 Answers 3
I think you want something like:
for name in found:
print(name, useraccounts[name]['totalscore'])
answered Feb 9, 2014 at 20:29
jonrsharpe
123k31 gold badges278 silver badges489 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can build on what you had before:
scores = [useraccounts[k]['totalscore'] for k in useraccounts if useraccounts[k]['class'] == '12']
# scores = [ list of scores ]
answered Feb 9, 2014 at 20:38
Hai Vu
41.5k16 gold badges75 silver badges106 bronze badges
Comments
If you only want the totalscore for those specific keys:
totals = [(key,value['totalscore') for key, value in useraccounts.items() if value['class'] == '12']
answered Feb 9, 2014 at 21:25
wwii
23.9k7 gold badges42 silver badges81 bronze badges
Comments
lang-py