Create dictionary
- Create dictionary directly
names = {'姓名': '阿肆', '年龄': 18, '爱好': '吃饭'}
print(names)
- Convert an object of sequence type into a dictionary through the function dict()
info = [('姓名', '阿肆'), ('年龄', 18,), ('爱好', '吃饭')]
print(type(info))
# 通过函数dict()将序列类型的对象转换为字典
info_1 = dict(info)
print(type(info_1))
print(info_1)
Note: Dictionary elements are unordered, so the output result is not unique
info_2 = dict([['1', "我"], ["2", "love"], ["3", 'YOU']])
eLnfo = dict((('1',300),('2',390), ('3',900)))
print(info_2)
print(eLnfo)
-Create dictionary with method fromkeys()
gInfo = {}.fromkeys(('a','b','c'),"一gioa我哩giao")
print(gInfo)
Note: The elements in the dictionary are stored unordered and can be sorted using the sorted() function
Basic operations on dictionaries
- sort
info_2 = dict([['1', "我"], ["2", "love"], ["3", 'YOU']])
print(sorted(info_2))
- Key value lookup
info_2 = dict([['1', "我"], ["2", "love"], ["3", 'YOU']])
print(info_2['2'])
- Update some values_1
info_2 = dict([['1', "我"], ["2", "love"], ["3", 'YOU']])
print(info_2)
info_2['1'] = 'I'
print(info_2)
Note: The keys in the dictionary cannot be updated (hashable). If you set a tuple as a key, you must restrict the elements of the tuple at all levels to be immutable.
- Add dictionary elements
info_2 = dict([['1', "我"], ["2", "love"], ["3", 'YOU']])
info_2['4'] = 'giao'
info_2 = dict([['1', "我"], ["2", "love"], ["3", 'YOU']])
info_2['4'] = 'giao'
info_2['5'] = ['阿 giao','红绿灯','阿远']
- Dictionary member judgment
info_2 = dict([['1', "我"], ["2", "love"], ["3", 'YOU']])
print('3' in info_2)
- Delete a dictionary or a key value of a dictionary
del(info_2)
info_2 = dict([['1', "我"], ["2", "love"], ["3", 'YOU']])
print('3' in info_2)
info_2['4'] = 'giao'
info_2['5'] = ['阿 giao','红绿灯','阿远']
del(info_2['5'])
Dictionary built-in functions
function | Function |
---|---|
dict | Function to create dictionary |
only (volume) | Returns the length of the dictionary (number of items) |
hash(obj) | Determine whether obj is hashable |
Dictionary methods
take several commonly used methods as examples
method | Function |
---|---|
keys() | Returns all key values of the dictionary |
painful() | $12 |
catheter | $1 |