简体   繁体   中英

How to get python list first element id

I have a list

MENU_Items = [ {  "ID":0x3B08, "Description":"Read Levelling Status\t\t"},    
                { "ID":0x3B39, "Description":"Read Air system control module state"},
                { "ID":0x3B3A, "Description":"Read Movement inhibit state\t"},     
                { "ID":0x3B3B, "Description":"Read Target height status\t\t"}]

Input = 1

MENU_Items[Input - 1]

I am getting the result as below:

{'ID': 15112, 'Description': 'Read Levelling Status\t\t'}

I want to extract only 'ID' as a output

I am trying something like this MENU_Items[Input - 1].ID

Its not working.

MENU_Items[Input - 1] will you first element of array first element which is a object. ['ID'] instead of .ID will give you id of that object

So, use MENU_Items[Input - 1]['ID']

So why not do something like this:

MENU_Items = [ {  "ID":0x3B08, "Description":"Read Levelling Status\t\t"},
            { "ID":0x3B39, "Description":"Read Air system control module state"},
            { "ID":0x3B3A, "Description":"Read Movement inhibit state\t"},
            { "ID":0x3B3B, "Description":"Read Target height status\t\t"}]

print(MENU_Items[0]["ID"])

The output would be

15112

To do this with user input, you can simply do:

info = int(input("Please enter which ID you wish to access: "))

x = info - 1

print(MENU_Items[x]["ID"])

Your output would be determined based on what they selected. I really wouldn't go this route though as there is no error handling, and you are not guaranteed they are entering an int which will cause an error as well. I'm just showing you a down and dirty quick example of how it could be done.

 >>> MENU_Items = [ {  "ID":0x3B08, "Description":"Read Levelling Status\t\t"},    
...                 { "ID":0x3B39, "Description":"Read Air system control module state"},
...                 { "ID":0x3B3A, "Description":"Read Movement inhibit state\t"},     
...                 { "ID":0x3B3B, "Description":"Read Target height status\t\t"}]

for input = 1,search for index = 0

>>> MENU_Items[0]
{'ID': 15112, 'Description': 'Read Levelling Status\t\t'}
>>> MENU_Items[0]['ID']
15112

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM