python字典以“鍵-值對”形式存在,所有的元素放在一對大括號“{}”中;
字典中的“鍵”是不允許重復,“值”是可以重復的.
以下總結了3A dictionary construction method
一、直接賦值法
使用=將一個字典賦值給一個變量,That is, you can create a dictionary variable.
# # 直接賦值
a = {
}
b = {
'a': 1, 2: 'a', 1: 2, "b": 1, '''c''': 1}
print('空字典:', a, type(a))
print('字典b:', b, type(b))
空字典:{} <class ‘dict’>
字典b :{‘a’: 1, 2: ‘a’, 1: 2, ‘b’: 1, ‘c’: 1}<class ‘dict’>
注:Use single quotes in dictionaries、雙引號、三引號都可以,這點跟jsonThe format data is different,jsonFormat data can only use double quotes.
二、內置函數dict()
使用內置函數dict快速創建字典
**用法1:**創建空字典
# 內置函數dict()
a = dict()
print(a, type(a))
結果:{} <class ‘dict’>
**用法2:**將2A list format data is combined into a dictionary
# 將2A list of data is combined into a dictionary
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dict1 = dict(zip(keys, values))
print('結果:', dict1)
結果:{‘a’: 1, ‘b’: 2, ‘c’: 3}
注:When combining dictionaries using this method,要保證2lists are the same length.
**用法3:**根據給定的“鍵-值對”創建字典
# Creates a dictionary from the given key-value pairs
dict1 = dict(a=1, b=2, c=3, d='a')
print('結果:', dict1)
結果:{‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: ‘a’}
**用法4:**The given content is“鍵”,創建“值”為空的字典
# # The given content is the key,Creates a list with an empty value
dict1 = dict.fromkeys(['a', 'b', 'c'])
dict2 = dict.fromkeys({
'a', 'b', 'c'})
dict3 = dict.fromkeys(('a', 'b', 'c'))
print('結果1:', dict1)
print('結果2:', dict2)
print('結果3:', dict3)
結果1:{‘a’: None, ‘b’: None, ‘c’: None}
結果2:{‘c’: None, ‘b’: None, ‘a’: None}
結果3:{‘a’: None, ‘b’: None, ‘c’: None}
注:dict.fromkeys()The value type inside can be a list、集合、元組.
**用法5:**創建所有“鍵”對應的“值”相同的字典
# Create a dictionary with all keys corresponding to the same value
dict1 = dict.fromkeys(['a', 'b', 'c'], 1)
dict2 = dict.fromkeys(['a', 'b', 'c'], [1,2])
print('值全為1的字典:', dict1)
print('值全為[1,2]的字典:', dict2)
值全為1的字典:{‘a’: 1, ‘b’: 1, ‘c’: 1}
值全為[1,2]的字典:{‘a’: [1, 2], ‘b’: [1, 2], ‘c’: [1, 2]}
三、字典推導式
Create a dictionary using dictionary comprehensions
# Create a dictionary using dictionary comprehensions
dict1 = {
key:values for (key, values) in []}
dict2 = {
key: values for (key, values) in zip(['a', 'b', 'c'], [1, 2, 'a'])}
print('結果1:', dict1)
print('結果2:', dict2)
結果1:{}
結果2:{‘a’: 1, ‘b’: 2, ‘c’: ‘a’}
以上就是構建python字典的常見用法,Different usages can be selected according to actual needs.
—end—