鉴于这个元组:
my_tuple = ('chess', ['650', u'John - Tom'])
我想创建字典,其中chess
是关键。它应该导致:
my_dict = {'chess': ['650', u'John - Tom']}
我有这段代码
my_dict = {key: value for (key, value) in zip(my_tuple[0], my_tuple[1])}
但它有缺陷并导致:
{'c': '650', 'h': u'John - Tom'}
你可以帮我修理一下吗?
答案 0 :(得分:4)
您始终可以使用2个值从元组列表(或单个元组)创建字典。
像这样:
>>> my_tuple = ('chess', ['650', u'John - Tom'])
>>> d = dict([my_tuple])
>>> d
{'chess': ['650', u'John - Tom']}
以这种简单的方式,您还可以获得元组列表......
>>> my_tuple_list = [('a','1'), ('b','2')]
>>> d = dict(my_tuple_list)
>>> d
{'a': '1', 'b': '2'}
答案 1 :(得分:3)
如果您的元组看起来像这样:(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']}
使用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']}
如果元组中的项目数不是那么大:
In [27]: { k : v for k,v in zip( my_tuple[::2],my_tuple[1::2] )}
Out[27]: {'chess': ['650', 'John - Tom']}
使用迭代器:
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']}
答案 2 :(得分:3)
>>> 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]}
答案 3 :(得分:2)
>>> my_tuple = ('a', [1, 2], 'b', [3, 4])
>>> dict(zip(*[iter(my_tuple)]*2))
{'a': [1, 2], 'b': [3, 4]}
对于您的特定情况:
{my_tuple[0]: my_tuple[1]}