2022年 11月 10日

python字典添加字典_Python添加到字典

python字典添加字典

Python dictionary is one of the built-in data types. Dictionary elements are key-value pairs.

Python词典是内置数据类型之一。 字典元素是键值对。

Python添加到字典 (Python add to Dictionary)

There is no explicitly defined method to add a new key to the dictionary. If you want to add a new key to the dictionary, then you can use assignment operator with dictionary key.

没有明确定义的方法可以向字典添加新键。 如果要向字典添加新键,则可以将赋值运算符与字典键一起使用。

dict[key] = value

Note that if the key already exists, then the value will be overwritten.

请注意,如果键已经存在,则该值将被覆盖。

Let’s look at a simple example to add new keys to a dictionary.

让我们看一个简单的示例,将新键添加到字典中。

  1. d = {'a': 1, 'b': 2}
  2. print(d)
  3. d['a'] = 100 # existing key, so overwrite
  4. d['c'] = 3 # new key, so add
  5. d['d'] = 4
  6. print(d)

Output:

输出:

  1. {'a': 1, 'b': 2}
  2. {'a': 100, 'b': 2, 'c': 3, 'd': 4}

What if we want to add a key only if it’s not present in the dictionary. We can use if condition to achieve this.

如果仅当字典中不存在键时我们想要添加键,该怎么办? 我们可以使用if条件来实现这一目标。

  1. if 'c' not in d.keys():
  2. d['c'] = 300
  3. if 'e' not in d.keys():
  4. d['e'] = 5
  5. print(d)

Output:

输出:

{'a': 100, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

Notice that ‘c’ value is not changed because of if condition.

注意,由于if条件,’c’值不会更改。

That’s all for adding keys to a dictionary in python.

这就是为python中的字典添加键的全部。

翻译自: https://www.journaldev.com/23232/python-add-to-dictionary

python字典添加字典