在循环中如何在字典中添加值?

时间:2019-06-05 16:08:54

标签: python python-2.7 loops dictionary

我有一个字典,根据我拥有的值,我想创建另一个“变量”;并放入字典中我能够创建另一个变量,但是我试图将其放入字典中却无法正常工作。我的代码是:

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

如果任何人有任何解决方案。 谢谢!

3 个答案:

答案 0 :(得分:0)

一种方法是制作要为每个元组添加的值的字典,这将简化例如将avar_a一起使用,并使用它来创建新的字典,如

mydict = {'1':('a','example'),'2':('b','example'),'3':('c','example'),'4':('d','example')}

def to_use(dictionary):

    # Mapping of element to add to tuple
    mapping = {'a': 'var_a', 'b': 'test_b', 'c': 'var_c', 'd': 'test_d'}

    #Iterate through dictionary
    for key, val in dictionary.iteritems():
        #For each key, add a 1 element-tuple to each value
        dictionary[key] = val + (mapping[val[0]],)

    return dictionary

print(to_use(mydict))

输出将为

{'1': ('a', 'example', 'var_a'), 
'2': ('b', 'example', 'test_b'), 
'3': ('c', 'example', 'var_c'), 
'4': ('d', 'example', 'test_d')}

答案 1 :(得分:0)

我认为代码有多个问题。 让我尝试一一解决。

1)元组是不可变的 您的字典值是元组,因此无法更改。 您可以选择将其更改为列表,方法是['a','example'],而不是('a','example')

在循环期间将它们替换为新的元组。

dictionary[key] = val + (new,)

2)您正在使用if len(val) == 1:检查长度1。对于您的示例数据,这永远都是不正确的。因此,当您到达new时就没有new_dict[key.lower()].append(new)变量。

我建议删除if语句。

3)您从未将new_dict声明为字典,因此new_dict[key.lower()].append(new)失败。

使用元组尝试以下代码:

mydict = {'1':('a','example'),'2':('b','example'),'3':('c','example'),'4':('d','example')}

def to_use (dictionary):
    for key, val in dictionary.iteritems():
        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'
        else:
            new = None
        if new is not None:
            dictionary[key] = val + (new,)

to_use(mydict)

或以下使用列表的代码:

mydict = {'1':['a','example'],'2':['b','example'],'3':['c','example'],'4':['d','example']}

def to_use (dictionary):
    for key, val in dictionary.iteritems():
        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'
        else:
            new = None
        if new is not None:
            dictionary[key].append(new)

to_use(mydict)

两者都应按预期工作。

答案 2 :(得分:0)

我找到了解决方案,方法是将我创建的新字典声明为defaultdict(list)。

感谢您的帮助!