Convert a simple tuple to a dictionary

I have an even tuple with type elements ('a','b','c','d','e','f')that I want to convert to a dictionary containing elements such as ['a':'b', 'c':'d', 'e':'f'].

I tried to use dict(tuple), but that did not help. I just started learning Python and any help would be very noticeable.

+4
source share
5 answers

It looks like you are trying to group a tuple into pairs and then drive them out of these pairs. There are two ways to do this.


The first is clipping:

zip(t[::2], t[1::2])

" ", start:stop:step. - ::2, ( ) ( ) 2, 0, 2 4. - 1::2, , 1 , 1, 3 5.

. Lists. (, , , ).


-, :

i = iter(t)
zip(i, i)

i , , , . , # 0, # 1, # 2, # 3 ..

. Iterators. . a > , (, , ).


('a', 'b'), ('c', 'd'), ('e', 'f'), dict:

dict(zip(t[::2], t[1::2]))

, ?

, , . .

, , (, , ), .

, , .

+4

dict:

t = ('a','b','c','d','e','f')
d = {t[i]:t[i+1] for i in range(0,len(t),2)}

,

range(0,len(t),2)

[0, 2, 4]
+1

:

t = ('a','b','c','d','e','f')
dict(t[i:i+2] for i in xrange(0, len(t), 2))
=> {'a': 'b', 'c': 'd', 'e': 'f'}
+1
>>> tup = ('a','b','c','d','e','f')
>>> dct = dict(zip(tup[::2], tup[1::2]))
{'a': 'b', 'c': 'd', 'e', 'f'}

0
def tup2dict():
    tup = ('a','b','c','d','e','f')
    print ({i:j for (i,j) in zip(tup,tup[1:])[::2]})

Thanks to iterating-over-every-two-elements-in-a-list and python-dictionary-comprehensionn .

-1
source

All Articles