2

给定这个元组:

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'}

你能帮我修一下吗?

4

4 回答 4

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'}
于 2013-04-29T11:06:50.450 回答
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']}

使用字典理解:

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']}
于 2013-04-29T11:05:26.670 回答
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]}
于 2013-04-29T11:16:11.907 回答
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]}
于 2013-04-29T11:04:22.527 回答