【问题标题】:How to add a value in a dictionary while looping through it?如何在遍历字典时在字典中添加值?
【发布时间】: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


【解决方案1】:

一种方法是为每个元组创建一个要添加的值的字典,这将简化例如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')}

【讨论】:

  • 谢谢 Devesh,但遗憾的是我无法手动进行字典映射,但我有成千上万种可能性。这段代码的想法是至少创建这个映射字典,因为之后我可以处理它。但即便如此,我也做不到。
  • 但是你的千种可能性必须列在某个地方,比如在一个文本文件中,你可以用它来创建映射字典,这比有千种情况要好得多
  • 我列出了第一个值的长度为 1、2 的情况,然后我放了 >2 的内容以涵盖所有可能性,因为我无法预测它们的长度。即使在 excel 文件中,我也无法涵盖所有​​可能性。我的程序涵盖了所有内容,现在我只需搜索在键和我创建的新变量之间创建一个字典。
  • 哪个程序涵盖了可能性,您也可以使用 itertools.product 或 itertools.combinations 生成您的可能性。看看docs.python.org/3/library/itertools.html
  • 嗨@LoC 我的建议对你有意义吗?如果是,请考虑支持答案:)
【解决方案2】:

我认为代码存在多个问题。 让我试着一一解决。

1) 元组是不可变的 您的字典值是元组,因此无法更改。 您可以或者将它们更改为['a','example'] 而非('a','example') 的列表。

在循环期间用新元组替换它们。

dictionary[key] = val + (new,)

2) 您正在使用 if len(val) == 1: 检查长度是否为 1。对于您的示例数据,这绝不是真的。因此,当您到达new_dict[key.lower()].append(new) 时,没有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)

两者都应该按您的预期工作。

【讨论】:

  • 您好编码诗人,感谢您的反馈!你是对的,这是长度的问题,我已经纠正了。之后我试过你的代码,但什么也没发生,这告诉我: TypeError: can only concatenate list (not "tuple") to list 当我尝试创建一个新字典时:newdict[key] = val + (新,)什么都没有发生,新字典是空的..
  • @LoC 我可能应该为这两个选项更清楚地标记 Or。您可能混合了这两种解决方案。我的意思是让您或者将值从元组更改为列表,或者使用dictionary[key] = val + (new,)。确保您将原始 mydict 值与代码一起使用,而不是修改后的值。我修改了答案以包含两个版本。我希望这能说清楚。
【解决方案3】:

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

感谢您的帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 2018-01-01
    • 2019-06-04
    • 1970-01-01
    • 2011-12-22
    • 2017-01-18
    相关资源
    最近更新 更多