【问题标题】:Appending a Dictionary Value that is a Tuple in Python在 Python 中附加作为元组的字典值
【发布时间】: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


【解决方案1】:

我想我可能拥有它!

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)

【讨论】:

    【解决方案2】:

    使用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)
    

    【讨论】:

      猜你喜欢
      • 2014-06-29
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 2017-01-15
      • 1970-01-01
      • 2021-12-21
      • 2013-07-12
      • 1970-01-01
      相关资源
      最近更新 更多