Uuid
Uuid

Reputation: 2546

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 )

Upvotes: 2

Views: 3903

Answers (4)

Cool-T
Cool-T

Reputation: 106

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]))

Upvotes: 3

user4815162342
user4815162342

Reputation: 155236

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.

Upvotes: 15

Asterisk
Asterisk

Reputation: 3574

tuple = ('name1','value1','name2','value2','name3','value3')
d = {}
for i in range(0, len(tuple), 2):
    d[tuple[i]] = tuple[i+1]
print d

Upvotes: 2

Jun HU
Jun HU

Reputation: 3314

just do a simple loop.

my_dic = {}
tuple = ('name1','value1','name2','value2','name3','value3')
if len(tuple) % 2 == 1:
    my_dic[tuple[-1]] = None
for i in range(0, len(tuple) - 1, 2):
    my_dic[tuple[i]] = tuple[i + 1]
print my_dic

Upvotes: 2

Related Questions