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

Python Dicts - print the value rather than the key

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


    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 Posts: 10,664 ✭✭✭✭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 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 Posts: 880 ✭✭✭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 Posts: 10,664 ✭✭✭✭maccored


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

    pfft ... pesky details :pac:


Advertisement