【发布时间】:2014-11-19 20:03:41
【问题描述】:
我正在尝试制作一个接受用户输入的 python 字典,将其拆分为两个索引的列表,将第二个索引作为字典键,将第一个索引作为字典值 - 但转换为元组。希望这是有道理的!我让它工作了,但是当我使用相同的键输入另一个输入时,我希望将新值附加到字典中已经存在的元组中。我知道元组是不可变的并且没有附加(或者我认为)所以我需要撒什么魔法才能让它添加到字典中的元组中?
到目前为止我的代码是:
desserts = {}
name_vote = input ('Name:vote ')
while name_vote != '':
no_colon_name_vote = name_vote.replace(":", " ")
name, vote = no_colon_name_vote.split()
name = tuple([name])
if vote not in desserts:
desserts[vote] = name
else:
desserts[vote].append(name) #this is where I'm hitting a brick wall
name_vote = input ('Name:vote ')
print(desserts)
我想要的两个输入的输出应该是
Name:vote Luke:icecream
Name:vote Bob:icecream
Name:vote
{'icecream': ('Luke', 'Bob')}
【问题讨论】:
-
如果您需要有序的可变元素集合,我建议使用列表而不是元组。
-
你应该小心你
split的方式,因为如果有人输入像Bill Clinton: Yes这样的名字,那么你的代码会抛出错误 -
两个 cmets 上的分数公平,但该活动遵循有关如何将元组用作值的大量说明......并且它规定名称只能作为名字输入
-
您不能追加到元组,因为它是不可变的,但如果您真的打算使用元组而不是列表,您可以这样做
deserts[vote] += name
标签: python dictionary tuples