Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Python Dicts - print the value rather than the key

  • 18-10-2018 1:55pm
    #1
    Registered Users, Registered Users 2 Posts: 10,748 ✭✭✭✭


    Im missing something pretty simple Im assuming.
    mydict = {'apple': 'non citrus', 'orange': 'non citrus', 'pear': 'non citrus', 'lime': 'citrus', 'plum': 'non citrus'}
    

    Thats the dictionary.

    I want to select those that are citrus. i can use the key (print (mydict ) ), but I would need to know which fruit was citrus first and have had the dict printed first so I could select.

    How do I get it to select the key from the value, rather than the value from the key?


Comments

  • Registered Users, Registered Users 2 Posts: 10,748 ✭✭✭✭maccored


    typical - spent days searching for an answer and the minute I put it up on boards, I find the solution:
    print(list(mydict.keys())[list(mydict.values()).index('citrus')])
    


  • Registered Users, Registered Users 2 Posts: 911 ✭✭✭heffsarmy


    Your solution does work as it won't select all key, value, try 'non citrus' and you will only select orange...this  will select all key values of 'non citrus'
    [font=Consolas, "Courier New", monospace]for key,value in mydict.items():
    if value == 'non citrus':
    print key[/font]


    or a one liner

    print '\n'.join([key for key,value in mydict.items() if value == 'citrus'])


  • Registered Users, Registered Users 2 Posts: 897 ✭✭✭moycullen14


    maccored wrote: »
    Im missing something pretty simple Im assuming.
    mydict = {'apple': 'non citrus', 'orange': 'non citrus', 'pear': 'non citrus', 'lime': 'citrus', 'plum': 'non citrus'}
    

    Thats the dictionary.

    I want to select those that are citrus. i can use the key (print (mydict ) ), but I would need to know which fruit was citrus first and have had the dict printed first so I could select.

    How do I get it to select the key from the value, rather than the value from the key?

    All I noticed was that you had orange as non-citrus :eek:


  • Registered Users, Registered Users 2 Posts: 10,748 ✭✭✭✭maccored


    All I noticed was that you had orange as non-citrus :eek:

    pfft ... pesky details :pac:


Advertisement