gpt4 book ai didi

python - 字典理解问题

转载 作者:行者123 更新时间:2023-11-28 19:44:44 24 4
gpt4 key购买 nike

给定这个元组:

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

你能帮我解决一下吗?

最佳答案

您始终可以从具有 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'}

关于python - 字典理解问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16277002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com