Python's dict dictionary structure operation method
This article mainly introduces the operation method of Python's dict dictionary structure. Learning notebook. The operation of dictionary is the basic knowledge for introductory learning of Python. Friends who need it can refer to
1. Dictionary Basic method
1. Create a new dictionary
1) Create an empty dictionary
>>> dict1={} >>> dict2=dict() >>> dict1,dict2 ({}, {})
2), initialize a value when creating a new one
>>> dict1={1:'a',2:'b',3:'c'} >>> dict1 {1: 'a', 2: 'b', 3: 'c'}
3), use tuple
>>> dict1=dict([(1,'a'),(2,'b'),(3,'c')]) >>> dict1 {1: 'a', 2: 'b', 3: 'c'}
2. Obtaining method
1), get(key) Get the value corresponding to a key from the dictionary and return value
>>> dict1={1:'a',2:'b',3:'c'} >>> dict1.get(1) 'a'
If it does not exist in the dictionary, return a NoneType
>>> type(dict1.get(4)) <type 'NoneType'>
If the required key value does not exist, specify another value to return
>>> dict1.get(4,'not found') 'not found'
2), keys () Get all the key values in the dictionary and return a list
>>> dict1.keys() [1, 2, 3]
3), values() corresponds to the keys() method, and returns the keys in the dictionary List of all values
>>> dict1.values() ['a', 'b', 'c']
4), items() returns a tuple corresponding to (key, value)
>>> dict1.items() [(1, 'a'), (2, 'b'), (3, 'c')]
5), iterkeys(), itervalues(), iteritems() also obtain all key, value, (key, value) ancestors respectively, but they no longer return a list, but an iterator
>>> for key in dict1.iterkeys(): print key 1 2 3
3. Method of setting dictionary value
1) The direct method is
>>> dict1[4]='d' >>> dict1 {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
However, this method is that if the key value I want to add is already in the dictionary, then the original one will be overwritten. The value
>>> dict1[4]='e' >>> dict1 {1: 'a', 2: 'b', 3: 'c', 4: 'e'}
2), setdefault(key, value) The advantage of this method is that if the inserted key does not exist in the dictionary, then insert it into the dictionary and Return the value. Otherwise, if it exists in the dictionary, then the existing value will be returned and will not be overwritten.
>>> dict1 {1: 'a', 2: 'b', 3: 'c', 4: 'e'} >>> dict1.setdefault(5,'f') 'f' >>> dict1.setdefault(5,'g') 'f' >>> dict1 {1: 'a', 2: 'b', 3: 'c', 4: 'e', 5: 'f'}
4. Delete the dictionary
1) pop(key) deletes an item of the specified key and successfully returns the value of the deleted item. If it does not exist, an exception will be thrown. Therefore, when using this method, you must judge whether the key is Exists, or catch this exception
>>> def pop_key(d,key): try: d.pop(key) print "sucess" except: print "key is not in dict" >>> dict1 {1: 'a', 2: 'b'} >>> pop_key(dict1,3) key is not in dict
>>> def sub_dict2(d,key): if d.has_key(key): d.pop(key) print "sucess" else:print "key is not in dict" >>> pop_key(dict1,3) key is not in dict
>>> list1=[1,2,3] >>> list2=['a','b','c'] >>> dict1=dict(zip(list1,list2)) >>> dict1 {1: 'a', 2: 'b', 3: 'c'}
>>> dict1 {1: 'a', 2: 'b', 3: 'c'} >>> dict1=dict([(1,'a'),(2,'b'),(3,'c')]) >>> dict1 {1: 'a', 2: 'b', 3: 'c'} >>> subkeys=[1,3] >>> def sub_dict(d,subkeys): return dict([(k,d.get(k)) for k in subkeys if k in d]) >>> print sub_dict(dict1,subkeys) {1: 'a', 3: 'c'}
>>> def invert_dict(d): return dict([(k,v) for v,k in d.iteritems()]) >>> print invert_dict(dict1) {'a': 1, 'c': 3, 'b': 2} >>>
1 ) has_key(key) Determine whether the key is in the dictionary
2) copy() returns a copy of the dictionary (the copy is a shallow copy)
>>> d2={1:[1],2:[2],3:[3]} >>> d3=d2.copy() >>> d3[1].append(4) >>> d2[1] [1, 4]
If you want to deep copy, you need to use copy.deepcopy(a)
>>> d2={1:[1],2:[2],3:[3]} >>> import copy >>> d3=copy.deepcopy(d2) >>> d3[1].append(4) >>> print d2[1] , d3[1] [1] [1, 4]
3) clear() clear dict
4) update(d) uses one dictionary to update another dictionary, which is somewhat similar to merging two dictionaries
>>> dict1={1: 'a', 2: 'b', 3: 'c'} >>> dict2={1:'x',4:'y'} >>> dict1.update(dict2) >>> dict1 {1: 'x', 2: 'b', 3: 'c', 4: 'y'} >>>
There are many ways to traverse a dictionary
1. Directly use dict>>> d {'a': 'aa', 'c': 'cc', 'b': 'bb'} >>> for i in d: print i,d[i] a aa c cc b bb
>>> for i,v in d.items(): print i,v a aa c cc b bb
##Of course you can also do this
>>> for (i,v) in d.items(): print i,v a aa c cc b bb
3. iteritems()
(I think it’s a better method)
>>> for k,v in d.iteritems(): print k,v a aa c cc b bb
1. One-click multi-value
Generally, dictionaries are mapped one-to-one, but if we need one-to-many mapping, such as a book, we need to count the number of pages where some words appear. Then, you can use list as the value of dict. This can be accomplished by using the setdefault() method
>>> d={'hello':[1,4,9],"good":[1,3,6]} >>> d {'good': [1, 3, 6], 'hello': [1, 4, 9]} >>> d.setdefault('good',[]).append(7) >>> d {'good': [1, 3, 6, 7], 'hello': [1, 4, 9]} >>> d.setdefault('bad',[]).append(2) >>> d {'bad': [2], 'good': [1, 3, 6, 7], 'hello': [1, 4, 9]} >>>
当然,如果写成一个函数话,就可以更方便的使用,
我们也可以利用set来代替list
>>> def addFunc(d,word,pag): d.setdefault(word,set()).add(pag) >>> d={'hello':set([1,4,9]),"good":set([1,3,6])} >>> addFunc(d,'hello',8) >>> d {'good': set([1, 3, 6]), 'hello': set([8, 1, 4, 9])} >>> addFunc(d,'bad',8) >>> d {'bad': set([8]), 'good': set([1, 3, 6]), 'hello': set([8, 1, 4, 9])}
2、利用字典完成简单工厂模式
字典的value不单单只是一些常见的字符串,数值,还可以是类和方法,比如我们就可以这样来实现简单工厂模式
>>> class cat(object): def __init__(self): print 'cat init' >>> class dog(object): def __init__(self): print 'dag init' >>> d={'cat':cat,'dog':dog} >>> def factoryFunc(d,name): if name in d: return d[name]() else: raise Exception("error") >>> cat=factoryFunc(d,'cat') cat init
另外一个例子,利用变量来控制执行的函数
>>> def deal_cat(): print 'cat run!!' >>> def deal_dog(): print 'dag run!!' >>> d={'cat':deal_cat ,'dog':deal_dog } >>> animal='cat' >>> d[animal]() cat run!!
更多Python的dict字典结构操作方法相关文章请关注PHP中文网!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
