【问题标题】:How to add to python dictionary without replacing如何在不替换的情况下添加到python字典
【发布时间】:2015-05-28 14:15:12
【问题描述】:

我的当前代码是category1[name]=(number) 但是,如果出现相同的名称,字典中的值将被新数字替换,我将如何制作它而不是替换值,而是保留原始值并使用新的value 也被添加,现在给 key 两个值,谢谢。

【问题讨论】:

  • 一个键只有一个值,你需要将值设为元组或列表等
  • @Calum 是正确的,并且可能应该复制他/她的评论作为答案。您需要更改值的表示形式以适应您所需的语义。
  • 提示:collections.defaultdict(list)

标签: python python-2.7 dictionary key


【解决方案1】:

我想这是最简单的方法:

category1 = {}
category1['firstKey'] = [7]
category1['firstKey'] += [9]
category1['firstKey']

应该给你:

[7, 9]

所以,只需使用数字列表而不是数字。

【讨论】:

    【解决方案2】:

    您可以创建一个字典,在其中将键映射到值列表,您希望在其中将新值附加到存储在每个键的值列表中。

               d = dict([])
               d["name"] = 1
               x = d["name"]
               d["name"] = [1] + x
    

    【讨论】:

      【解决方案3】:

      根据您的期望,您可以检查name(您的字典中的一个键)是否已经存在。如果是这样,您也许可以将其当前值更改为一个列表,其中包含以前的值和新值。

      我没有对此进行测试,但也许你想要这样的东西:

      mydict = {'key_1' : 'value_1', 'key_2' : 'value_2'}
      
      another_key = 'key_2'
      another_value = 'value_3'
      
      if another_key in mydict.keys():
          # another_key does already exist in mydict
          mydict[another_key] = [mydict[another_key], another_value]
      
      else:
          # another_key doesn't exist in mydict
          mydict[another_key] = another_value
      

      多次这样做时要小心!如果您想存储两个以上的值,您可能需要添加另一个检查 - 以查看 mydict[another_key] 是否已经是一个列表。如果是这样,请使用.append() 为其添加第三个、第四个、... 值。

      否则你会得到一个嵌套列表的集合。

      【讨论】:

        【解决方案4】:

        您的问题有点难以理解。

        我想你想要这个:

        >>> d[key] = [4]
        >>> d[key].append(5)
        >>> d[key]
        [4, 5]
        

        【讨论】:

          【解决方案5】:

          键只有一个值,您需要将值设为元组或列表等

          如果你知道你将为一个键设置多个值,那么我建议你让这些值在创建时能够处理这个问题

          【讨论】:

            【解决方案6】:

            您必须使字典指向列表而不是数字,例如,如果类别 cat1 有两个数字:

            categories["cat1"] = [21, 78]
            

            为确保您将新号码添加到列表中而不是替换它们,请在添加之前先检查它是否存在:

            cat_val = # Some value
            if cat_key in categories:
                categories[cat_key].append(cat_val)
            else:
                # Initialise it to a list containing one item
                categories[cat_key] = [cat_val]
            

            要访问这些值,您只需使用 categories[cat_key],如果有一个值为 12 的键,则返回 [12],如果该键有两个值,则返回 [12, 95]

            请注意,如果您不想存储重复的键,则可以使用集合而不是列表:

            cat_val = # Some value
            if cat_key in categories:
                categories[cat_key].add(cat_val)
            else:
                # Initialise it to a set containing one item
                categories[cat_key] = set(cat_val)
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2022-01-26
              • 2020-01-23
              • 2017-09-01
              • 1970-01-01
              • 2020-07-18
              • 2015-01-19
              • 1970-01-01
              • 2020-08-04
              相关资源
              最近更新 更多