Reputation: 175
I have a even length tuple having elements like ('a','b','c','d','e','f')
which I want to convert to dictionary having elements like ['a':'b', 'c':'d', 'e':'f']
.
I tried using dict(tuple)
but that wasn't helping. I have just started learning Python and any help will be highly appreciable.
Upvotes: 4
Views: 150
Reputation: 365697
It looks like you're trying to group the tuple into pairs, and then make a dict out of those pairs. There are two ways to do this.
The first is zipping slices:
zip(t[::2], t[1::2])
This is called an "extended slice", which is of the form start:stop:step
. The first one is ::2
, so it has the default start (the beginning of the tuple) and stop (the end of the tuple), and a step of 2, so it gets elements 0, 2, and 4. The second one is 1::2
, so it's the same, but it starts at 1 instead of the default, so it gets elements 1, 3, and 5.
See the tutorial section on Lists for more details. (Of course you're using a tuple, not a list, but they both slice the same way.)
The second is zipping an iterator with itself:
i = iter(t)
zip(i, i)
Since the two references to i
are both the same iterator, whenever you advance one, it advances both. So, the first one gets #0, then the second gets #1, then the first gets #2, the second #3, and so on.
See the tutorial section on Iterators for more details. Also see How grouper works, which explains a more general version of this idea (or at least tries to).
Either way, you get ('a', 'b')
, then ('c', 'd')
, then ('e', 'f')
, so you can just pass that to dict
:
dict(zip(t[::2], t[1::2]))
So, which one is better?
Slicing is probably easier to understand. It's also usually faster.
However, slicing doesn't work on arbitrary iterables, just sequences, it wastes memory on big inputs (you're essentially making a complete extra copy of the sequence), and it's a little harder to generalize.
You should learn how both of them work so you can choose appropriately.
Upvotes: 4
Reputation: 1416
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.
Upvotes: -1
Reputation: 11039
>>> tup = ('a','b','c','d','e','f')
>>> dct = dict(zip(tup[::2], tup[1::2]))
{'a': 'b', 'c': 'd', 'e', 'f'}
This should do the trick
Upvotes: 0
Reputation: 236004
Try this:
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'}
Upvotes: 1
Reputation: 34146
You can use a dict comprehension:
t = ('a','b','c','d','e','f')
d = {t[i]:t[i+1] for i in range(0,len(t),2)}
Note that the part
range(0,len(t),2)
will generate a list of the form
[0, 2, 4]
Upvotes: 1