>>> my_tuple = ('a', [1, 2], 'b', [3, 4])
>>> dict(zip(*[iter(my_tuple)]*2))
{'a': [1, 2], 'b': [3, 4]}
For your particular case though:
{my_tuple[0]: my_tuple[1]}
Вопрос
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?
Решение 4
>>> my_tuple = ('a', [1, 2], 'b', [3, 4])
>>> dict(zip(*[iter(my_tuple)]*2))
{'a': [1, 2], 'b': [3, 4]}
For your particular case though:
{my_tuple[0]: my_tuple[1]}
Другие советы
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'}
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']}
>>> my_tuple = ('chess', ['650', u'John - Tom'])
>>> it = iter(my_tuple)
>>> {k: next(it) for k in it}
{'chess': ['650', u'John - Tom']}
>>> my_tuple = ('a', [1, 2], 'b', [3, 4])
>>> it = iter(my_tuple)
>>> {k: next(it) for k in it}
{'a': [1, 2], 'b': [3, 4]}