how can I convert a tuple into a key value pairs dynamically?
Let's say I have:
tuple = ('name1','value1','name2','value2','name3','value3')
I want to put it into a dictionary:
dictionary = { name1 : value1, name2 : value2, name3 : value3 )
Convert the tuple to key-value pairs and let the dict constructor build a dictionary:
it = iter(tuple_)
dictionary = dict(zip(it, it))
The zip(it, it) idiom produces pairs of items from an otherwise flat iterable, providing a sequence of pairs that can be passed to the dict constructor. A generalization of this is available as the grouper recipe in the itertools documentation.
If the input is sufficiently large, replace zip with itertools.izip to avoid allocating a temporary list. Unlike expressions based on mapping t[i] to [i + 1], the above will work on any iterable, not only on sequences.
dictionary = {tuple[i]: tuple[i + 1] for i in range(0, len(tuple), 2)}
Another simple way :
dictionary = dict(zip(tuple[::2],tuple[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