简体   繁体   中英

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 )

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

另一个简单方法:

dictionary = dict(zip(tuple[::2],tuple[1::2]))

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
tuple = ('name1','value1','name2','value2','name3','value3')
d = {}
for i in range(0, len(tuple), 2):
    d[tuple[i]] = tuple[i+1]
print d

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM