Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dict comprehension issue

Given this tuple:

my_tuple = ('chess', ['650', u'John - Tom'])

I want to create dictionary where chess is the key. It should result in:

my_dict = {'chess': ['650', u'John - Tom']}

I have this code

my_dict = {key: value for (key, value) in zip(my_tuple[0], my_tuple[1])} 

but it's flawed and results in:

{'c': '650', 'h': u'John - Tom'}

Can you please help me fixing it?

like image 229
nutship Avatar asked Jun 13 '26 01:06

nutship


2 Answers

You can always create a dictionary from a list of tuples, (or single tuple) with 2 values.

Like so:

>>> my_tuple = ('chess', ['650', u'John - Tom'])
>>> d = dict([my_tuple])
>>> d
{'chess': ['650', u'John - Tom']}

In this easy way you could also have a list of tuples...

>>> my_tuple_list = [('a','1'), ('b','2')]
>>> d = dict(my_tuple_list)
>>> d
{'a': '1', 'b': '2'}
like image 99
Inbar Rose Avatar answered Jun 14 '26 14:06

Inbar Rose


Something like this , if your tuple looks like : (key1,value1,key2,value2,...)

In [25]: dict((my_tuple[i],my_tuple[i+1]) for i in xrange(0,len(my_tuple),2))
Out[25]: {'chess': ['650', 'John - Tom']}

using dict-comprehension:

In [26]: {my_tuple[i]: my_tuple[i+1] for i in xrange(0,len(my_tuple),2)}
Out[26]: {'chess': ['650', 'John - Tom']}

if the number of items in tuple are not so large:

In [27]: { k : v for k,v in zip( my_tuple[::2],my_tuple[1::2] )}
Out[27]: {'chess': ['650', 'John - Tom']}

Using an iterator:

In [36]: it=iter(my_tuple)

In [37]: dict((next(it),next(it)) for _ in xrange(len(my_tuple)/2))
Out[37]: {'chess': ['650', 'John - Tom']}
like image 44
Ashwini Chaudhary Avatar answered Jun 14 '26 13:06

Ashwini Chaudhary



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!