【发布时间】:2019-10-21 04:28:33
【问题描述】:
我有一本字典,根据我拥有的值,我想创建另一个“变量”;并将其放入字典中。我能够创建另一个变量,但我试图将它放入字典中的方法不起作用。我的代码是:
mydict = {'1':('a','example'),'2':('b','example'),'3':('c','example'),'4':('d','example')}
def to_use (dictionary):
for key, val in dictionary.iteritems():
if len(val) == 1:
if val[0] == 'a':
new = 'var_a'
elif val[0] == 'b':
new = 'test_b'
elif val[0] == 'c':
new = 'var_c'
elif val[0] == 'd':
new = 'test_d'
new_dict[key.lower()].append(new)
to_use(mydict)
函数中的最后一行应该创建另一个字典(但不是),因为我不确定是否可以在不创建新字典的情况下访问我的最终字典。 我想要的是:
mydict = {'1':('a','example','var_a'),'2':('b','example','test_b'),'3':('c','example','var_c'),'4':('d','example','test_d')}
如果有人有任何解决方案.. 谢谢!
【问题讨论】:
-
你不能追加到元组,因为它们是不可变的。你需要列表。
-
(but is not)那么,为什么它没有按预期工作?阅读并发布错误消息,它们是线索。 -
它给了我一个密钥错误,返回找到的第一个密钥。我知道元组是不可变的,但我的想法是首先创建一个新字典。
标签: python python-2.7 loops dictionary