【问题标题】:How can I add new keys to a dictionary?如何在 Python 中向字典添加新键?
【发布时间】:2010-11-04 17:18:48
【问题描述】:

是否可以在创建 Python 字典后为其添加键?

它似乎没有.add() 方法。

【问题讨论】:

  • 要么使用公认的答案:d['mynewkey'] = 'mynewvalue' 要么你可以使用 val = d.setdefault('mynewkey', 'mynewvalue')
  • 如果只使用[] = ,如果key不存在,会自动添加key。
  • Re @cs95,这也会创建一个带有附加键的新字典:dict(existing_dict, new_key=new_val) per stackoverflow.com/a/46647897/1840471
  • @MaxGhenis 谢谢,这适用于 python here。

标签: python dictionary lookup


【解决方案1】:

您通过为该键分配一个值来在字典上创建一个新的键/值对

d = {'key': 'value'}
print(d)  # {'key': 'value'}

d['mynewkey'] = 'mynewvalue'

print(d)  # {'key': 'value', 'mynewkey': 'mynewvalue'}

如果键不存在,则添加并指向该值。如果存在,则覆盖它指向的当前值。

【讨论】:

  • 这和.update()方法有什么区别?什么时候更好?
  • @hegash d[key]=val 语法因为它更短并且可以将任何对象作为键处理(只要它是可散列的),并且只设置一个值,而 .update(key1=val1, key2=val2) 如果你想要更好同时设置多个值,只要键是字符串(因为 kwargs 被转换为字符串)。 dict.update 也可以取另一个字典,但我个人不喜欢显式创建一个新字典来更新另一个字典。
  • 如何在嵌套字典中添加元素。喜欢 php $foo[ ] = [ . . . . ]
  • 拜托,谁能解释一下这个答案和 append() 之间的区别,例如:a_dict["a"].append("hello")
  • 基于If it exists, the current value it points to is overwritten. 我怎样才能优雅地检查我尝试添加信息的密钥是否已经存在然后引发异常?
【解决方案2】:

要同时添加多个键,请使用dict.update()

>>> x = {1:2}
>>> print(x)
{1: 2}

>>> d = {3:4, 5:6, 7:8}
>>> x.update(d)
>>> print(x)
{1: 2, 3: 4, 5: 6, 7: 8}

对于添加单个密钥,接受的答案具有较少的计算开销。

【讨论】:

  • 创建一个字典来更新一个键的效率太低了。仅当您拥有超过 1 个密钥时才执行此操作(可能存在一个阈值,高于该阈值最好创建一个 dict)
  • @Jean-FrançoisFabre 这是示例代码。您真的不应该将答案视为涵盖所有情况。
  • 它给人一种错误的印象,认为这是添加一个键的首选方式。
  • @Jean-FrançoisFabre 由于dict ordering is guaranteed in Python 3.7+ (and provided in 3.6+),当顺序很重要时,这可能是添加单个键的首选方式。
  • 如果您创建另一个键,例如 x[-1] = 44-1 的值也将结束。无论如何,答案已经过编辑,现在好多了。当字典可能包含许多项目时,使用字典进行更新是很好的选择。
【解决方案3】:

我想整合有关 Python 字典的信息:

创建一个空字典

data = {}
# OR
data = dict()

用初始值创建字典

data = {'a': 1, 'b': 2, 'c': 3}
# OR
data = dict(a=1, b=2, c=3)
# OR
data = {k: v for k, v in (('a', 1), ('b',2), ('c',3))}

插入/更新单个值

data['a'] = 1  # Updates if 'a' exists, else adds 'a'
# OR
data.update({'a': 1})
# OR
data.update(dict(a=1))
# OR
data.update(a=1)

插入/更新多个值

data.update({'c':3,'d':4})  # Updates 'c' and adds 'd'

Python 3.9+:

更新操作符 |= 现在适用于字典:

data |= {'c':3,'d':4}

在不修改原件的情况下创建合并字典

data3 = {}
data3.update(data)  # Modifies data3, not data
data3.update(data2)  # Modifies data3, not data2

Python 3.5+:

这使用了一个名为字典解包的新功能。

data = {**data1, **data2, **data3}

Python 3.9+:

合并运算符 | 现在适用于字典:

data = data1 | {'c':3,'d':4}

删除字典中的项目

del data[key]  # Removes specific element in a dictionary
data.pop(key)  # Removes the key & returns the value
data.clear()  # Clears entire dictionary

检查一个键是否已经在字典中

key in data

遍历字典中的对

for key in data: # Iterates just through the keys, ignoring the values
for key, value in d.items(): # Iterates through the pairs
for key in d.keys(): # Iterates just through key, ignoring the values
for value in d.values(): # Iterates just through value, ignoring the keys

从两个列表创建字典

data = dict(zip(list_with_keys, list_with_values))

【讨论】:

  • 3.9 中的“OR”运算符| 似乎解决了我的python dicts 没有任何构建器模式的问题。
  • 最好提到“更新一个条目”的各种选项,使用“更新”的选项有创建临时字典的开销。
【解决方案4】:

“是否可以在创建 Python 字典后为其添加键?它似乎没有 .add() 方法。”

是的,这是可能的,它确实有一个方法可以实现这一点,但你不想直接使用它。

为了演示如何以及如何不使用它,让我们使用 dict 文字创建一个空 dict,{}

my_dict = {}

最佳实践 1:下标符号

要使用单个新键和值更新此字典,您可以使用提供项目分配的the subscript notation (see Mappings here)

my_dict['new key'] = 'new value'

my_dict 现在是:

{'new key': 'new value'}

最佳实践 2:update 方法 - 2 种方式

我们还可以使用the update method 高效地使用多个值更新字典。我们可能在这里不必要地创建了一个额外的dict,所以我们希望我们的dict 已经被创建并来自或被用于其他目的:

my_dict.update({'key 2': 'value 2', 'key 3': 'value 3'})

my_dict 现在是:

{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value'}

使用 update 方法执行此操作的另一种有效方法是使用关键字参数,但由于它们必须是合法的 Python 单词,所以不能有空格或特殊符号或以数字开头的名称,但许多人认为这是为字典创建键的更易读的方法,在这里我们当然避免创建额外不必要的dict

my_dict.update(foo='bar', foo2='baz')

my_dict 现在是:

{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value', 
 'foo': 'bar', 'foo2': 'baz'}

所以现在我们已经介绍了更新dict 的三种 Pythonic 方式。


魔术方法,__setitem__,以及为什么要避免它

还有另一种更新不应该使用的dict 的方法,它使用__setitem__ 方法。下面是一个如何使用__setitem__ 方法将键值对添加到dict 的示例,并演示了使用它的性能不佳:

>>> d = {}
>>> d.__setitem__('foo', 'bar')
>>> d
{'foo': 'bar'}


>>> def f():
...     d = {}
...     for i in xrange(100):
...         d['foo'] = i
... 
>>> def g():
...     d = {}
...     for i in xrange(100):
...         d.__setitem__('foo', i)
... 
>>> import timeit
>>> number = 100
>>> min(timeit.repeat(f, number=number))
0.0020880699157714844
>>> min(timeit.repeat(g, number=number))
0.005071878433227539

所以我们看到使用下标符号实际上比使用__setitem__ 快得多。做 Pythonic 的事情,即按照预期的方式使用语言,通常更具可读性和计算效率。

【讨论】:

  • 2020 年的差异不大(在我的机器上,下标为 1.35 毫秒,d.__setitem__ 为 2 毫秒),但结论(尤其是最后一句话)仍然合理。将方法名称查找提升到循环外将时间减少到大约 1.65 毫秒;其余的差异可能主要是由于不可避免的 Python 调用机制开销。
【解决方案5】:
dictionary[key] = value

【讨论】:

    【解决方案6】:

    如果你想在字典中添加字典,你可以这样做。

    示例:向您的词典和子词典添加新条目

    dictionary = {}
    dictionary["new key"] = "some new entry" # add new dictionary entry
    dictionary["dictionary_within_a_dictionary"] = {} # this is required by python
    dictionary["dictionary_within_a_dictionary"]["sub_dict"] = {"other" : "dictionary"}
    print (dictionary)
    

    输出:

    {'new key': 'some new entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}}
    

    注意: Python 要求您首先添加一个子

    dictionary["dictionary_within_a_dictionary"] = {}
    

    在添加条目之前。

    【讨论】:

    • 这与 php.net 手册页中的大多数 cmets 所提出的问题一样无关紧要......
    • 没有什么能阻止你在一行中这样做:dictionary = {"dictionary_within_a_dictionary": {"sub_dict": {"other" : "dictionary"}}}(或者如果dictionary已经是一个字典,dictionary["dictionary_within_a_dictionary"] = {"sub_dict": {"other" : "dictionary"}}
    【解决方案7】:

    常规语法是d[key] = value,但如果您的键盘缺少方括号键,您也可以这样做:

    d.__setitem__(key, value)
    

    事实上,定义__getitem____setitem__ 方法可以让你自己的类支持方括号语法。请参阅Dive Into Python, 5.6. Special Class Methods

    【讨论】:

    • 如果没有键盘上的括号键,我会发现使用 python 编程非常困难。
    • 这是我能找到的在列表理解中设置字典值的唯一方法。谢谢
    • @chrisstevens 如果你想在理解中设置一个值,我使用的 hack 是[a for a in my_dict if my_dict.update({'a': 1}) is None]
    • 很好奇...这是常见的(即缺少方括号)吗?
    • @chrisstevens @JeremyLogan 为什么在可以使用字典推导时使用列表推导? {v: k for k, v in my_dict.items() if <some_conditional_check>}
    【解决方案8】:

    您可以创建一个:

    class myDict(dict):
    
        def __init__(self):
            self = dict()
    
        def add(self, key, value):
            self[key] = value
    
    ## example
    
    myd = myDict()
    myd.add('apples',6)
    myd.add('bananas',3)
    print(myd)
    

    给予:

    >>> 
    {'apples': 6, 'bananas': 3}
    

    【讨论】:

      【解决方案9】:

      This popular question 解决了合并字典 ab功能方法。

      这里有一些更直接的方法(在 Python 3 中测试)...

      c = dict( a, **b ) ## see also https://stackoverflow.com/q/2255878
      c = dict( list(a.items()) + list(b.items()) )
      c = dict( i for d in [a,b] for i in d.items() )
      

      注意:上面的第一种方法只有在b 中的键是字符串时才有效。

      要添加或修改单个元素b 字典将只包含那个元素...

      c = dict( a, **{'d':'dog'} ) ## returns a dictionary based on 'a'
      

      这相当于...

      def functional_dict_add( dictionary, key, value ):
         temp = dictionary.copy()
         temp[key] = value
         return temp
      
      c = functional_dict_add( a, 'd', 'dog' )
      

      【讨论】:

      • 关于 Python BDFL (here) 中第一种方法的有趣评论。
      • c = dict( a, **{'d':'dog'} ) 最好写成c = dict(a, d='dog'),只要密钥是已知的而不是计算出来的。
      【解决方案10】:

      假设您想生活在不可变的世界中,并且想修改原始文件,但想要创建一个新的dict,这是向原始文件添加新密钥的结果。

      在 Python 3.5+ 中,您可以:

      params = {'a': 1, 'b': 2}
      new_params = {**params, **{'c': 3}}
      

      Python 2 等效项是:

      params = {'a': 1, 'b': 2}
      new_params = dict(params, **{'c': 3})
      

      在以下任何一个之后:

      params 仍然等于{'a': 1, 'b': 2}

      new_params 等于 {'a': 1, 'b': 2, 'c': 3}

      有时您不想修改原始文件(您只想要添加到原始文件的结果)。 我发现这是一个令人耳目一新的替代方案:

      params = {'a': 1, 'b': 2}
      new_params = params.copy()
      new_params['c'] = 3
      

      params = {'a': 1, 'b': 2}
      new_params = params.copy()
      new_params.update({'c': 3})
      

      参考:What does `**` mean in the expression `dict(d1, **d2)`?

      【讨论】:

      • 在与我的一位支持函数式编程的同事的长时间交谈中,提出了一个很好的观点。上述方法的一个缺点是,如果阅读代码的人不熟悉 Python 中的 **(很多人不熟悉),那么发生的事情就不清楚了。有时您会倾向于使用功能较少的方法以获得更好的可读性。
      • 我们无法预测读者知道 Python 语言的哪个子集,因此可以假设他们知道整个语言,因此他们会在文档中搜索他们不知道的部分。
      【解决方案11】:

      还有一个名字奇怪,行为古怪,但仍然很方便的dict.setdefault()

      这个

      value = my_dict.setdefault(key, default)
      

      基本上就是这样做的:

      try:
          value = my_dict[key]
      except KeyError: # key not found
          value = my_dict[key] = default
      

      例如,

      >>> mydict = {'a':1, 'b':2, 'c':3}
      >>> mydict.setdefault('d', 4)
      4 # returns new value at mydict['d']
      >>> print(mydict)
      {'a':1, 'b':2, 'c':3, 'd':4} # a new key/value pair was indeed added
      # but see what happens when trying it on an existing key...
      >>> mydict.setdefault('a', 111)
      1 # old value was returned
      >>> print(mydict)
      {'a':1, 'b':2, 'c':3, 'd':4} # existing key was ignored
      

      【讨论】:

        【解决方案12】:

        更新字典有两种方法:

        1. 使用方括号表示法 ([])

          my_dict = {}
          my_dict['key'] = 'value'
          
        2. 使用update() 方法

          my_dict = {}
          my_dict.update({'key': 'value'})
          

        【讨论】:

          【解决方案13】:

          如果您不是加入两个字典,而是将新的键值对添加到字典中,那么使用下标表示法似乎是最好的方法。

          import timeit
          
          timeit.timeit('dictionary = {"karga": 1, "darga": 2}; dictionary.update({"aaa": 123123, "asd": 233})')
          >> 0.49582505226135254
          
          timeit.timeit('dictionary = {"karga": 1, "darga": 2}; dictionary["aaa"] = 123123; dictionary["asd"] = 233;')
          >> 0.20782899856567383
          

          但是,例如,如果您想添加数千个新的键值对,您应该考虑使用 update() 方法。

          【讨论】:

            【解决方案14】:

            这个问题已经得到了令人作呕的回答,但是自从我 comment 获得了很大的吸引力,这是一个答案:

            在不更新现有字典的情况下添加新键

            如果您在这里试图弄清楚如何添加一个键并返回一个 new 字典(不修改现有字典),您可以使用以下技术来做到这一点

            python >= 3.5

            new_dict = {**mydict, 'new_key': new_val}
            

            蟒蛇
            new_dict = dict(mydict, new_key=new_val)
            

            请注意,使用这种方法,您的密钥需要遵循 python 中的rules of valid identifier names

            【讨论】:

              【解决方案15】:

              这是我在这里没有看到的另一种方式:

              >>> foo = dict(a=1,b=2)
              >>> foo
              {'a': 1, 'b': 2}
              >>> goo = dict(c=3,**foo)
              >>> goo
              {'c': 3, 'a': 1, 'b': 2}
              

              您可以使用字典构造函数和隐式扩展来重建字典。此外,有趣的是,此方法可用于控制字典构建期间的位置顺序(post Python 3.6)。 In fact, insertion order is guaranteed for Python 3.7 and above!

              >>> foo = dict(a=1,b=2,c=3,d=4)
              >>> new_dict = {k: v for k, v in list(foo.items())[:2]}
              >>> new_dict
              {'a': 1, 'b': 2}
              >>> new_dict.update(newvalue=99)
              >>> new_dict
              {'a': 1, 'b': 2, 'newvalue': 99}
              >>> new_dict.update({k: v for k, v in list(foo.items())[2:]})
              >>> new_dict
              {'a': 1, 'b': 2, 'newvalue': 99, 'c': 3, 'd': 4}
              >>> 
              

              以上是使用字典理解。

              【讨论】:

                【解决方案16】:

                首先检查key是否已经存在:

                a={1:2,3:4}
                a.get(1)
                2
                a.get(5)
                None
                

                然后你可以添加新的键和值。

                【讨论】:

                  【解决方案17】:

                  你可以使用方括号:

                  my_dict = {}
                  my_dict["key"] = "value"
                  

                  或者你可以使用 .update() 方法:

                  my_another_dict = {"key": "value"}
                  my_dict = {}
                  my_dict.update(my_another_dict)
                  

                  【讨论】:

                    【解决方案18】:

                    这是一个简单的方法!

                    your_dict = {}
                    your_dict['someKey'] = 'someValue'
                    

                    这将在your_dict 字典中添加一个新的key: value 对,其中包含key = someKeyvalue = somevalue

                    如果your_dict 中已存在键somekey 的值,您也可以使用这种方式更新该值。

                    【讨论】:

                    • 只是想澄清一下,因为事情会不时发生很大变化,尤其是在编程方面
                    【解决方案19】:
                    your_dict = {}
                    

                    添加新密钥:

                    1. your_dict[key]=value

                    2. your_dict.update(key=value)

                    【讨论】:

                      【解决方案20】:

                      我认为指出 Python 的 collections 模块也很有用,该模块由许多有用的字典子类和包装器组成,可简化 字典中数据类型的添加和修改,特别是defaultdict

                      调用工厂函数提供缺失值的dict子类

                      如果您使用的字典总是包含相同的数据类型或结构,例如列表字典,这将特别有用。

                      >>> from collections import defaultdict
                      >>> example = defaultdict(int)
                      >>> example['key'] += 1
                      >>> example['key']
                      defaultdict(<class 'int'>, {'key': 1})
                      

                      如果键还不存在,defaultdict 将给定的值(在我们的例子中为10)作为初始值分配给字典(通常在循环中使用)。因此,此操作做了两件事:它向字典添加一个新键(根据问题),并且如果该键还不存在,则分配该值。标准字典,这会引发错误,因为 += 操作正在尝试访问尚不存在的值:

                      >>> example = dict()
                      >>> example['key'] += 1
                      Traceback (most recent call last):
                        File "<stdin>", line 1, in <module>
                      KeyError: 'key'
                      

                      如果不使用defaultdict,添加新元素的代码量会更多,可能看起来像:

                      # This type of code would often be inside a loop
                      if 'key' not in example:
                          example['key'] = 0  # add key and initial value to dict; could also be a list
                      example['key'] += 1  # this is implementing a counter
                      

                      defaultdict也可以用于复杂的数据类型,例如listset

                      >>> example = defaultdict(list)
                      >>> example['key'].append(1)
                      >>> example
                      defaultdict(<class 'list'>, {'key': [1]})
                      

                      添加元素会自动初始化列表。

                      【讨论】:

                        【解决方案21】:

                        添加一个字典(key,value)类。

                        class myDict(dict):
                        
                            def __init__(self):
                                self = dict()
                        
                            def add(self, key, value):
                                #self[key] = value # add new key and value overwriting any exiting same key
                                if self.get(key)!=None:
                                    print('key', key, 'already used') # report if key already used
                                self.setdefault(key, value) # if key exit do nothing
                        
                        
                        ## example
                        
                        myd = myDict()
                        name = "fred"
                        
                        myd.add('apples',6)
                        print('\n', myd)
                        myd.add('bananas',3)
                        print('\n', myd)
                        myd.add('jack', 7)
                        print('\n', myd)
                        myd.add(name, myd)
                        print('\n', myd)
                        myd.add('apples', 23)
                        print('\n', myd)
                        myd.add(name, 2)
                        print(myd)
                        

                        【讨论】:

                          【解决方案22】:

                          dict 类中有一个更新方法应该适合你。

                          考虑:

                          # dictionary = {"key":"value"}
                          

                          但是没有任何方法,您可以通过创建一个新值来添加一个键,如下所示:

                          dictionary['newkey'] = 'newvalue'
                          

                          或使用更新https://www.python.org/dev/peps/pep-0584/#dict-update

                          dictionary.update({'newkey':'newvalue'})
                          

                          【讨论】:

                            猜你喜欢
                            • 2010-11-04
                            • 1970-01-01
                            • 1970-01-01
                            • 2018-05-27
                            • 1970-01-01
                            • 2020-06-10
                            • 1970-01-01
                            相关资源
                            最近更新 更多