Python Basic-Usage of Dictionary (Dictionary), related operations, addition, deletion, modification, nesting, traversal, sorting

@

Dictionary Dictory

  • Store data in the form of key-value.
  • Python performs a hash calculation on the key, and the result of the calculation is the memory address used to store the value.
  • Dictionaries are stored out of order .
  • The value of the dictionary, the stored value is accessed by the result of the hash
  • The list is actually similar to the array that C puts it bluntly. It is a continuous memory space. When searching, deleting, and inserting data, it needs to be processed by the offset of the subscript.
  • The dictionary is not a connected memory space, but the key is hashed to obtain the memory address for storage.
  • Since the hash storage is required, the key must be unique . If the key is the same, the same memory address will be obtained, which will conflict
  • The "key" must be an immutable type, like a string, integer, tuple, etc., like a list, a dictionary is a variable type and is not hashable.
  • "Value" can be a variable type, it can be a list, tuple, or dictionary.

Create a dictionary

An ordinary dictionary

dictory = {"name":"taohuadaozhu","age":30,"gendle":"male","company":"baidu","department":"IT"}
  • dictory: variable name
  • {}: Use curly brackets
  • "key": "value": Use a colon to connect a key-value pair
  • , Use "," to separate between different key-value pairs

A nested dictionary

dictory = {"name":"taohuadaozhu","age":30,"gendle":"male","company":{"baidu":"Bigfirm","character":"Privately owned"},"department":"IT"}

dict () function to create a dictionary (not commonly used)

dictory = dict((("name","feihuang"),("age",30)))
  • A pair of key, value is enclosed in a (), you can also use []
  • Use "," to separate key and value
  • Different key and value pairs are enclosed in parentheses and parentheses

Dictionary operation

increase

There are two methods:

Direct increase

  • Because the dictionary is unordered, there is no need to specify anything, just specify the added key
  • If the key already exists, directly change the value to the new specified value

Use setdefault () function to increase

  • If the new key is added, it is added directly.
  • If you add an existing key, it will not change the original value, which is relatively safe
  • setDefault () method with the return value can be saved to another variable success for returning modified so on

dictory = {"name":"taohuadaozhu","age":30}
print(dictory)

#增加一对键值
dictory["company"]="baidu"
print(dictory)

#增加时键为已经存在的键,如果用此种方法,则是直接将原来的值 进行了更改
dictory["age"]=18
print(dictory)



#使用setdefault() 方法来增加
dictory.setdefault("department","IT")
print(dictory)

#使用setdefault() 函数对已经存在的key进行更改
dictory.setdefault("age",20)
print(dictory)

"""
{'name': 'taohuadaozhu', 'age': 30}
{'name': 'taohuadaozhu', 'age': 30, 'company': 'baidu'}
{'name': 'taohuadaozhu', 'age': 18, 'company': 'baidu'}
{'name': 'taohuadaozhu', 'age': 18, 'company': 'baidu', 'department': 'IT'}
{'name': 'taohuadaozhu', 'age': 18, 'company': 'baidu', 'department': 'IT'}
"""

delete

del () directly deletes the sum of a key; if it directly follows the dictionary, the entire dictionary is deleted

dictory_baidu = {"name":"taohuadaozhu","age":30,"gendle":"male","company":{"baidu":"Bigfirm","character":"Privately owned"},"department":"IT"}
print(dictory_baidu)
del dictory_baidu["gendle"]
print(dictory_baidu)
dictory_baidu = {"name":"taohuadaozhu","age":30,"gendle":"male","company":{"baidu":"Bigfirm","character":"Privately owned"},"department":"IT"}
del dictory_baidu
print(dictory_baidu)

clear () directly clears all key-value pairs, leaving an empty dictionary

dictory_baidu = {"name":"taohuadaozhu","age":30,"gendle":"male","company":{"baidu":"Bigfirm","character":"Privately owned"},"department":"IT"}
dictory_baidu.clear()
print(dictory_baidu)

pop () deletes the corresponding key-value pair and returns the value corresponding to the key as the return value

dictory_baidu = {"name":"taohuadaozhu","age":30,"gendle":"male","company":{"baidu":"Bigfirm","character":"Privately owned"},"department":"IT"}
name = dictory_baidu.pop("name")
print(name)
print(dictory_baidu)

popitem () randomly deletes the corresponding key-value pairs, using both key and value as tuples as the return value

dictory_baidu = {"name":"taohuadaozhu","age":30,"gendle":"male","company":{"baidu":"Bigfirm","character":"Privately owned"},"department":"IT"}
name = dictory_baidu.popitem()
print(name)
print(dictory_baidu)

check

.values ​​() View all values

.keys () find all keys

.items () View all the keys and values, all found

dictory = {"name":"taohuadaozhu","age":30,"gendle":"male","company":{"baidu":"Bigfirm","character":"Privately owned"},"department":"IT"}

#查出所有的键(key),但是查出来的并不是一个列表,但是可以转换成列表
print(dictory.keys())       			#查看dictory这个字典的所有的键
print(dictory.values())     			# 查看所有的value
print(dictory.items())      			#显示所有的键值对儿

print(type(dictory.keys())) 			#查看dictory.keys() 数据类型

dictory_key = list(dictory.keys()) 		#强制转换为列表,并将返回值 赋值给dictory_key这个变量
dictory_value = list(dictory.values())  #将values强制转换为列表

print(type(dictory_key))           		#查看dictory_key的数据类型,这里为list列表了。
print(type(dictory_value))           	#查看dictory_value的数据类型,这里为list列表了。


"""以下为输出内容
dict_keys(['name', 'age', 'gendle', 'company', 'department'])
dict_values(['taohuadaozhu', 30, 'male', {'baidu': 'Bigfirm', 'character': 'Privately owned'}, 'IT'])
dict_items([('name', 'taohuadaozhu'), ('age', 30), ('gendle', 'male'), ('company', {'baidu': 'Bigfirm', 'character': 'Privately owned'}), ('department', 'IT')])
<class 'dict_keys'>
<class 'list'>
<class 'list'>
"""

change

. update()

  • You can update a dictionary to another dictionary and merge a dictionary into another dictionary.
  • If the keys in the two dictionaries are duplicated, the updated value will be overwritten before the update
  • If the key is not in the original dictionary, add it to the dictionary
dictory_baidu = {"name":"taohuadaozhu","age":30,"gendle":"male","company":{"baidu":"Bigfirm","character":"Privately owned"},"department":"IT"}
dictory_xiaomi = {"iname":"feihuang","iage":29,"gendle":"male","company_cn":"xiaomi","department":"IT"}
#修改其中一个值,与前面讲的增加一样,如果已经有的key,则改key所对应的值,如果没有这个key,则直接修改其内容
dictory_baidu["age"]=18
print(dictory_baidu)
print(dictory_xiaomi)

#使用update()方法对字典进行更新
dictory_baidu.update(dictory_xiaomi)    # 将dictory_xiaomi合并到dictory_baidu中去,如果已原字典中已经有相同的key了,则直接替换为dictory_xiaomi中对应的key的value,如果没有key,则直接合并过去
print(dictory_baidu)
print(dictory_xiaomi)

"""
{'name': 'taohuadaozhu', 'age': 18, 'gendle': 'male', 'company': {'baidu': 'Bigfirm', 'character': 'Privately owned'}, 'department': 'IT'}
{'iname': 'feihuang', 'iage': 29, 'gendle': 'male', 'company_cn': 'xiaomi', 'department': 'IT'}
{'name': 'taohuadaozhu', 'age': 18, 'gendle': 'male', 'company': {'baidu': 'Bigfirm', 'character': 'Privately owned'}, 'department': 'IT', 'iname': 'feihuang', 'iage': 29, 'company_cn': 'xiaomi'}
{'iname': 'feihuang', 'iage': 29, 'gendle': 'male', 'company_cn': 'xiaomi', 'department': 'IT'}
"""

Other operations

dict.fromkeys (): Specify multiple keys, and then assign values ​​uniformly, which can be used for initialization

dictory = dict.fromkeys(["name1","name2","name3","name4"],"172.16.100.1")
print(dictory)
dictory = dict.fromkeys(["name1","name2","name3","name4"],["172.16.100.1","www.xiaomi.com"])
print(dictory)
"""
{'name1': '172.16.100.1', 'name2': '172.16.100.1', 'name3': '172.16.100.1', 'name4': '172.16.100.1'}
{'name1': ['172.16.100.1', 'www.xiaomi.com'], 'name2': ['172.16.100.1', 'www.xiaomi.com'], 'name3': ['172.16.100.1', 'www.xiaomi.com'], 'name4': ['172.16.100.1', 'www.xiaomi.com']}
"""

Dictionary nesting

There are dictionaries in the dictionary, but it is not limited to this. You can also nest lists like lists, tuples, etc.

dictory = {
    "Wudang":{
        "name":"ZhangSanfeng",
        "Age":103,
        "Skill":"Taiji"
    },
    "Emei":{
        "name": "Miejueshitai",
        "Age": 73,
        "Skill": "Emeijianfa"
    },
    "HuaShan":{
        "name": "Fengqingyang",
        "Age": 53,
        "Skill": "Dugujiujian"
    },
    "Mojiao":{
        "name": "Dongfangbubai",
        "Age": 63,
        "Skill": "xixingdafa"
    }
}
print(dictory)

“”“
#以下为输出的内容
{'Wudang': {'name': 'ZhangSanfeng', 'Age': 103, 'Skill': 'Taiji'}, 'Emei': {'name': 'Miejueshitai', 'Age': 73, 'Skill': 'Emeijianfa'}, 'HuaShan': {'name': 'Fengqingyang', 'Age': 53, 'Skill': 'Dugujiujian'}, 'Mojiao': {'name': 'Dongfangbubai', 'Age': 63, 'Skill': 'xixingdafa'}}
”“”

Modification of content after dictionary nesting

dictory["Wudang"]["name"]="zhangwuji"
print(dictory)
"""
{'Wudang': {'name': 'zhangwuji', 'Age': 103, 'Skill': 'Taiji'}, 'Emei': {'name': 'Miejueshitai', 'Age': 73, 'Skill': 'Emeijianfa'}, 'HuaShan': {'name': 'Fengqingyang', 'Age': 53, 'Skill': 'Dugujiujian'}, 'Mojiao': {'name': 'Dongfangbubai', 'Age': 63, 'Skill': 'xixingdafa'}}

"""

Dictionary sorting

By default, it is sorted by key. If you need to sort by value, you can sort by value in the "sorted (dictionary.value ())" list .

Dictionary traversal

  • 1. Only print the key
dictory_baidu = {"name":"taohuadaozhu","age":30,"gendle":"male","company":{"baidu":"Bigfirm","character":"Privately owned"},"department":"IT"}

for i in dictory_baidu:
    print(i)
print("==================================================")
"""
name
age
gendle
company
department
==================================================
"""
  • Print key and corresponding value, this method has high efficiency
for i in dictory_baidu:
    print(i,dictory_baidu[i])
print("==================================================")
"""
name taohuadaozhu
age 30
gendle male
company {'baidu': 'Bigfirm', 'character': 'Privately owned'}
department IT
==================================================
"""
  • The second method prints the key and the corresponding value, but the output is a tuple
for i in dictory_baidu.items():
    print(i)
print("==================================================")

"""
('name', 'taohuadaozhu')
('age', 30)
('gendle', 'male')
('company', {'baidu': 'Bigfirm', 'character': 'Privately owned'})
('department', 'IT')
==================================================
"""

  • The third method prints the key and the corresponding value, and uses two variables to output
for i,v in dictory_baidu.items():
    print(i,v)
print("==================================================")

"""
name taohuadaozhu
age 30
gendle male
company {'baidu': 'Bigfirm', 'character': 'Privately owned'}
department IT
==================================================
"""

Guess you like

Origin www.cnblogs.com/fei-huang/p/12741028.html