The content of this article is to introduce how to use dictionary in python? How to use python dictionary. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Dictionaries, like sets, are unordered and cannot be accessed through indexes, but only through keys.
The keys of the dictionary must be immutable data types, such as numbers, strings, tuples, etc. Mutable objects such as lists cannot be used as keys.
Create dictionary and add and remove dictionary:
#创建字典 a = {'name':'xiaobin','age':18} print(a) b = dict(name = 'xiaobin',age = '18') print(b) #字典的添加,键不重名的添加,重名的会覆盖更新 a['from'] = 'anhui' print(a) a.update({'hobby':'football','age':20}) print(a) #字典元素的去除 b = a.pop('age') print(b) print(a) 运行结果: {'name': 'xiaobin', 'age': 18} {'name': 'xiaobin', 'age': '18'} {'name': 'xiaobin', 'age': 18, 'from': 'anhui'} {'name': 'xiaobin', 'age': 20, 'from': 'anhui', 'hobby': 'football'} 18 {'name':'xiaobin'}
Modification of dictionary:
info = {'a':[1,2,4],'b':[4,5,6]} info['a'][2] = 3 print(info) 运行结果:{'a': [1, 2, 3], 'b': [4, 5, 6]}
Membership of dictionary:
#成员关系 a = {'a':1,'b':2} print('b' in a) 运行结果:True
Method of dictionary:
a = {'a':1,'b':2} print(a.keys()) print(a.values()) print(a.items()) 运行结果: dict_keys(['a', 'b']) dict_values([1, 2]) dict_items([('a', 1), ('b', 2)])
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study. For more related video tutorials, please visit: Python video tutorial, Python3 video tutorial, bootstrap video tutorial!
The above is the detailed content of How to use dictionary in python? Use of python dictionary. For more information, please follow other related articles on the PHP Chinese website!