drecute
drecute

Reputation: 758

Getting a list value from key/value pair

If I have a list with key/value pair, how do I get the value of the key?

I'm working with this code snippet:

>>> items = {'fees':[('status','pending'), ('timeout',60)], 'hostel':[('status',
 'pending'), ('timeout','120')]}
>>> print [items[i] for i in items.keys()]
[[('status', 'pending'), ('timeout', '120')], [('status', 'pending'), ('timeout'
, 60)]]
>>>

I'm expecting this:

# get timeout. I know this line is wrong
timeout = items.get(i)

# Put the transaction item in a queue at a specific timeout
# period

transaction_queue(i, block, timeout)

def transaction_queue(item, block=False, timeout):
    return queue.put(item, block, timeout)

Thanks for helping out.

I can't answer until 7 hours as at writing.

So, the answer is:

>>> for key, value in items.iteritems():
...     for val in value:
...             print "\t{0} : {1}".format(val[0], val[1])
...
        status : pending
        timeout : 120
        status : pending
        timeout : 60
>>>

Thanks to Vincent Vande Vyvre

Upvotes: 3

Views: 21088

Answers (2)

Anson
Anson

Reputation: 2674

You're already printing the values in your "print" statement, so I assume you just want to print the name of the keys.

This modification of your print statement will print the key names:

print [i for i in items.keys()]

Upvotes: 0

rumpel
rumpel

Reputation: 8300

I’m not sure I understand your question completely, but the easy solution is probably:

>>> dict(items['fees'])['status']
'pending'

Upvotes: 2

Related Questions