Home > Backend Development > Python Tutorial > How to add key-value pairs in python dictionary

How to add key-value pairs in python dictionary

(*-*)浩
Release: 2019-11-01 15:29:46
Original
22760 people have browsed it

How to add key-value pairs in python dictionary

Add key-value pairs

##First define an empty dictionary (recommended Learn: Python video tutorial)

>>> dic={}
Copy after login

Directly assign a value to a key that does not exist in the dictionary to add

>>> dic['name']='zhangsan'
>>> dic
{'name': 'zhangsan'}
Copy after login

If the key or This method can also be used if value is a variable

>>> key='age'
>>> value=30
>>> dic[key]=value
>>> dic
{'age': 30, 'name': 'zhangsan'}
Copy after login

Here you can see that the data in the dictionary are not arranged in order. If you are interested, you can search the data structure—— Hash table

Starting from python3.7, the dictionary is ordered according to the order of insertion. Modifying the value of an existing key does not affect the order. If a key is deleted and then added, the key will be added to the end. The dump(s)/load(s) of the standard json library are also ordered

You can also use the setdefault method of the dictionary

>>> dic.setdefault('sex','male')
'male'
>>> key='id'
>>> value='001'
>>> dic.setdefault(key,value)
'001'
>>> dic
{'id': '001', 'age': 30, 'name': 'zhangsan', 'sex': 'male'}
Copy after login

The above is the detailed content of How to add key-value pairs in python 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