Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Python Dicts - print the value rather than the key

  • 18-10-2018 02:55PM
    #1
    Registered Users, Registered Users 2 Posts: 10,793 ✭✭✭✭


    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,793 ✭✭✭✭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: 939 ✭✭✭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,793 ✭✭✭✭maccored


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

    pfft ... pesky details :pac:


Advertisement