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

How to add key-value pairs in python dictionary

(*-*)浩
(*-*)浩 Original
2019-10-31 13:25:24 22640browse

How to add key-value pairs in python dictionary

Add key-value pairs

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

>>> dic={}

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

>>> dic['name']='zhangsan' >>> dic {'name': 'zhangsan'}

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'}

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'}

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!

Statement:
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