Relevant usage in python dictionary

import random;

Create dictionary

dict1 = {'qq': '859444120', '明日科技': '859444120', '无语': 123456}
print(dict1)

Create an empty dictionary

dict2 = {}
dict3 = dict()
print(dict2 == dict3)  # 结果为True,表示两种都是空字典

zip mapping function

list1 = [i for i in range(10)]
list2 = [random.randint(0, 10) for i in range(10)]
dict4 = dict(zip(list1, list2))
print(dict4)

Another way to create a dictionary

dict5 = dict(yi=1, er=2, san=3, si=4)
print(dict5)

Another way to create a dictionary

tuple1 = ((1, 1), (2, 2), (3, 3))
dict4 = dict(tuple1)
print(dict4)  # 输出{1: 1, 2: 2, 3: 3}

Create a key is not empty, is empty dictionary

dict6 = dict.fromkeys(list1)
print(dict6)

The dictionary can be a key tuple values ​​may be a list

tuple1 = tuple((i for i in range(10)))
dict7 = {tuple1: list1}
print(dict7)

Delete dictionary

del dict7
try:
    print(dict7)
except Exception:
    print('dict7 已经被删除')  # 程序输出字典dict7已经被删除

Delete dictionary elements

dict6.clear()
print(dict6)

Access dictionary element

print(dict5['yi'])  # 输出1
try:
    print(dict5['wu'])  # 出现异常,因为dict5中没有键为'wu'的元素
except Exception:
    print('出现异常,因为dict5中没有键为\'wu\'的元素')
print(dict5['wu'] if '' in dict5 else '没有键为\'wu\'的元素')  # 通过这种方式也可以避免出现异常
'''dictionary.get(key,[default])'''
print(dict5.get('wu'))  # 通过这种方法也可以避免出现异常,当不存在时程序输出None
print(dict5.get('wu', "没有'wu'"))  # 程序输出没有wu

Traversal Dictionary

'''通过dictionary.items()方法可以获取一个键值对的列表'''
list3 = dict5.items()
for item in list3:
    print(item, end=" ")  # 程序输出('yi', 1) ('er', 2) ('san', 3) ('si', 4)
print()
for item in list3:
    print(item[0], end=" ")  # 获取键 程序输出yi er san si
print()
for item in list3:
    print(item[1], end=" ")  # 获取值 程序输出1 2 3 4
print()
for key, value in list3:
    print(key, ':', value, end=" ")  # 获取key value 程序输出yi : 1 er : 2 san : 3 si : 4
print(type(list3))

Add an element to the dictionary

dict5['wu'] = 5
print(dict5)  # {'yi': 1, 'er': 2, 'san': 3, 'si': 4, 'wu': 5}

Covering the original value of the same key

dict5['wu'] = 4
print(dict5)  # {'yi': 1, 'er': 2, 'san': 3, 'si': 4, 'wu': 4}

'' 'To delete the dictionary one key' ''

del dict5['wu']
print(dict5)  # {'yi': 1, 'er': 2, 'san': 3, 'si': 4}

When the delete key does not exist will be abnormal, so it is necessary to determine

if "wu" in dict5:
    del dict5["wu"]
else:
    print('不存在')  # 程序输出不存在

Dictionary derivations

dict8 = {i: random.randint(0, 10) for i in range(10)}
print(dict8)  # {0: 6, 1: 7, 2: 2, 3: 8, 4: 9, 5: 6, 6: 9, 7: 0, 8: 2, 9: 5}
Published 100 original articles · won praise 13 · views 3302

Guess you like

Origin blog.csdn.net/qq_44378358/article/details/104106252