Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

key value pairs from tuple in python

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 )
like image 622
Uuid Avatar asked Aug 02 '26 08:08

Uuid


2 Answers

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.

like image 182
user4815162342 Avatar answered Aug 04 '26 02:08

user4815162342


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]))
like image 24
Cool-T Avatar answered Aug 04 '26 02:08

Cool-T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!