Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value on a certain index, in a python list?

Tags:

python

I have a list which looks something like this

List = [q1,a1,q2,a2,q3,a3]

I need the final code to be something like this

dictionary = {q1:a1,q2:a2,q3:a3}

if only I can get values at a certain index e.g List[0] I can accomplish this, is there any way I can get it?

like image 256
Fahim Akhter Avatar asked Dec 22 '09 02:12

Fahim Akhter


2 Answers

Python dictionaries can be constructed using the dict class, given an iterable containing tuples. We can use this in conjunction with the range builtin to produce a collection of tuples as in (every-odd-item, every-even-item), and pass it to dict, such that the values organize themselves into key/value pairs in the final result:

dictionary = dict([(List[i], List[i+1]) for i in range(0, len(List), 2)])
like image 83
zzzeek Avatar answered Nov 15 '22 08:11

zzzeek


Using extended slice notation:

dictionary = dict(zip(List[0::2], List[1::2]))
like image 29
sth Avatar answered Nov 15 '22 08:11

sth