Home >Backend Development >Python Tutorial >Python dictionary operations

Python dictionary operations

高洛峰
高洛峰Original
2016-11-17 13:45:251392browse

Starting today, I plan to write something every week to record my learning and mark it myself.

Dictionary is the most flexible built-in data structure in Python. A dictionary is an unordered collection (the order of the dictionary is random to quickly perform key lookups). Python uses an optimized hashing algorithm to find keys; a dictionary is similar to that in Java. map, but there are not as many types as map in java (HashMap, TreeMap, etc.).

Common dictionary operations

Assignment

D = {}  # 空字典
D = {"name": "zhangsan", "age": 23}  # 包含2个项目的字典
D = {"fruit": {"apple": 2, "orange": 1}}  # 嵌套
D = dict.fromkeys(["a", "b"], 2)  # {'a': 2, 'b': 2}
D = dict(zip(["name", "age"], ["zhangsan", '23']))  # {'age': '23', 'name': 'zhangsan'}

Value

name = D["name"]
age = D.get("age", 0)  # 如果不存在age属性就取值为0
keys = D.keys()  # 获取键
values = D.values()  # 获取value
if 'name' in D:
    print "name is in D"

Delete

D.pop('sex')  # 根据key删除
del D['name']  # 根据key删除

Other operations

D_1 = {"sex": "male"}
D.update(D_1)  # 合并dict


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