在Python中附加作为元组的字典值

时间:2014-11-19 20:03:41

标签: python dictionary tuples

我试图创建一个获取用户输入的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')}

2 个答案:

答案 0 :(得分:0)

我想我可能有它!

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:
    original = desserts[vote]
    desserts[vote] = (original + name)
  name_vote = input ('Name:vote ')

print(desserts)

答案 1 :(得分:0)

使用list存储值和defaultdict会更容易,如果您要使用可变容器一直添加名称会更有意义:

from collections import defaultdict
desserts = defaultdict(list)
name_vote = input ('Name:vote ')
while name_vote != '':
    no_colon_name_vote = name_vote.replace(":", " ")
    name, vote = no_colon_name_vote.split()
    desserts[vote].append(name)  
    name_vote = input ('Name:vote ')
print(desserts)

如果你想要元组,你可以将列表转换为元组:

for k,v in desserts.iteritems():
    desserts[k] = tuple(v)