0

I am new to Python and I want to present a dropdownlist i.e. Netflix, Now TV, Amazon Prime etc using the optionmenu provided by TKinter. The dropdownlist should display the text values listed above but each item will have a unique identifier which I don't want to display in the dropdownlist. The data I get back from the API is as follows:

[{'id': 1, 'name': 'Netflix'}, {'id': 2, 'name': 'Now TV'}, {'id': 3, 'name': 'Amazon'}] and I want a list displayed like:

Netflix
Now TV
Amazon

When an item is selected I will want to select the id from the item selected so I can make an API call and get the full information.

In effect each item in the list will have the unique identifier but not displayed in the optionmenu.

What I have displayed in the optionmenu is: "{'id': 1, 'name': 'Netflix'} when I want just the name value "Netflix"

this is an extract of the code that populates the optionmenu and handles the selection.

accounts = accountsAPI.getAccounts()

def change(*args):
        selectedItem = var.get()
        print(selectedItem)
        if selectedItem in accounts:
                print(accounts.get())

var = StringVar(root)
var.trace("w",change)

dropDownMenuAccounts = OptionMenu(root,var,*accounts)
dropDownMenuAccounts.grid(row=0,column=1,  padx=10,pady=10)

Can anyone guide me in the right direction on how I can accomplish this.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
hebog
  • 1
  • Change your `list` of `dict` to a `list` of names: `accounts = [d['name' for d in accountsAPI.getAccounts()]` – stovfl Apr 23 '20 at 16:17
  • Hi Thanks for your response. How would I get the ID of the item using this expression. I need the ID so I can then get all information of the record but obviously I don't want to display the ID in the optionsmenu? – hebog Apr 23 '20 at 17:19
  • 1
    You have to create a new `dict` from the `list` of `dict`. `option = {d['name']: d['id'] for d in accountsAPI.getAccounts()} ; accounts = list(options) ; print(option[var.get()])` – stovfl Apr 23 '20 at 17:50
  • Thanks will give it a go. – hebog Apr 23 '20 at 18:21
  • Thanks stovfl with slight change to your solution i.e just this line of code options = {d['name']: d['id'] for d in passwordAPI.getPasswords()}; it works. – hebog Apr 24 '20 at 13:42

0 Answers0