Home > Enterprise >  Display only True values in a dictionary
Display only True values in a dictionary

Time:02-23

I am trying to display the permissions of a member from a dict as in

permdict = {
                    'Administrator': f'{member.guild_permissions.administrator}',
                    'Ban Members': f'{member.guild_permissions.ban_members}',
                    'Kick members': f'{member.guild_permissions.kick_members}'}

at this moment this will return something like :

{'Administrator': 'True', 'Ban Members': 'True', 'Kick members': 'True'}

or false if the user doesn't have these permissions, my goal is to be able to filter the keys which have True values, so if the user have just x/3 permissions (the dictionary will be bigger, but i don't want to proceed further unless i am able to solve my problem), to show just the Key with True value and if the user has none of the permissions in the dictionary it will return nothing or a string ex You have no moderation roles to dispaly and if some of the perms are present to display them just by key Administrator, Kick members etc. . . I didn't worked too much with bools inside dictionaries so i hoped i can find a solution here.

i also tried to combine it with .join:

 permdict = {'Administrator': f'{member.guild_permissions.administrator}',
                    'Ban Members': f'{member.guild_permissions.ban_members}',
                    'Kick members': f'{member.guild_permissions.kick_members}'}

 permf = ", ".join(permdict) ​

And the result was what i desired

Administrator, Ban Members, Kick members ​

but the problem was that even if the user didn't had these perms they will still be displayed. I feel like i'm quite close to find a solution but i can't figure it out

CodePudding user response:

Use a generator with a condition:

permf = ", ".join(key for key, value in permdict.items() if value == "True")
  • Related