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?
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)])
Using extended slice notation:
dictionary = dict(zip(List[0::2], List[1::2]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With