Zaks
Zaks

Reputation: 700

Extract value form list of tuples python

My list message looks as below :

msg = [('_SIZE', b'\\100'), ('_MODE', b'\\x00'), ('_EXPIRY', b'\\x1000')]

I want to extract value of _EXPIRY from this

Tried msg['_EXPIRY'], msg[0]['EXPIRY'] . What is the correct way to get the data

Upvotes: 0

Views: 948

Answers (2)

Bhagyesh Dudhediya
Bhagyesh Dudhediya

Reputation: 1856

One of the approach:

msg_list = [('_SIZE', b'\\100'), ('_MODE', b'\\x00'), ('_EXPIRY', b'\\x1000')]
for msg in msg_list:
    if (msg[0] == "_EXPIRY"):
        print (msg[1])
        break

Another approach can be to convert it into dict and access the key as below:

msg_list = [('_SIZE', b'\\100'), ('_MODE', b'\\x00'), ('_EXPIRY', b'\\x1000')]
try:
    msg_dict = dict(msg_list)
    print(msg_dict['_EXPIRY'])
except KeyError as ex:
    print (f"Entry for _EXPIRY does not exists")

Upvotes: 0

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

You probably want to access _EXPIRY but that needs to be cast as dict first before accessing. OR read it by index of list of tuple print(msg[2][1])

msg = [('_SIZE', b'\\100'), ('_MODE', b'\\x00'), ('_EXPIRY', b'\\x1000')]
msg_dict = dict(msg)
print(msg_dict['_EXPIRY'])

Upvotes: 6

Related Questions