Home > Backend Development > Python Tutorial > What are the ways to add elements to the dictionary?

What are the ways to add elements to the dictionary?

anonymity
Release: 2019-05-25 09:48:02
Original
17502 people have browsed it

Dictionary is another mutable container model and can store any type of object.

Each key-value (key=>value) pair in the dictionary is separated by a colon (:), each pair is separated by a comma (,), and the entire dictionary is included in curly braces ({}) , the format is as follows:

d = {key1 : value1, key2 : value2 }

The keys must be unique, but the values ​​do not have to be.

The value can be of any data type, but the key must be immutable, such as string, number or tuple.

A simple dictionary example:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

What are the ways to add elements to the dictionary?

Methods to add elements to the dictionary:

1. When the keys in the dictionary exist, they can be accessed by subscripting the dictionary name. Change the value corresponding to the key in the dictionary. If the key does not exist, an exception will be thrown. If you want to add elements directly to the dictionary, you can add dictionary elements directly using the dictionary name subscript value. If you only write the key and assign the key value later, an exception will be thrown.

>>>a=['apple','banana','pear','orange']
>>> a
['apple', 'banana', 'pear', 'orange']
>>> a={1:'apple',2:'banana',3:'pear',4:'orange'}
>>> a
{1: 'apple', 2: 'banana', 3: 'pear', 4: 'orange'}
>>> a[2]
'banana'
>>> a[5]
Traceback (most recent call last):
 File "<pyshell#31>", line 1, in <module>
 a[5]
KeyError: 5
>>> a[6]=&#39;grap&#39;
>>> a
{1: &#39;apple&#39;, 2: &#39;banana&#39;, 3: &#39;pear&#39;, 4: &#39;orange&#39;, 6: &#39;grap&#39;}
Copy after login

2. Use the update method to add the key-value pairs with corresponding keys in the dictionary to the current dictionary

>>> a
{1: &#39;apple&#39;, 2:&#39;banana&#39;, 3: &#39;pear&#39;, 4: &#39;orange&#39;, 6: &#39;grap&#39;}
>>>a.items()
dict_items([(1,&#39;apple&#39;), (2, &#39;banana&#39;), (3, &#39;pear&#39;), (4, &#39;orange&#39;), (6, &#39;grap&#39;)])
>>>a.update({1:10,2:20})
>>> a
{1: 10, 2: 20,3: &#39;pear&#39;, 4: &#39;orange&#39;, 6: &#39;grap&#39;}
#{1:10,2:20}替换了{1: &#39;apple&#39;, 2: &#39;banana&#39;}
Copy after login

The above is the detailed content of What are the ways to add elements to the dictionary?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template