Efficient use of Python dictionary skills are all here!

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/wcg541/article/details/100086779

Dictionary (dict) objects are the most common data structures Python

Community It has been jokingly said: "Python dictionary attempt to load the entire world."

The importance of the dictionary in Python is self-evident, here compiled a list of several on efficient use of dictionaries, Python developers can reasonably hope to use in everyday applications development, make the code more Pythonic.

1, with the key in the keyword checking whether there is

Zen of Python has a development philosophy is:

There should be one-- and preferably only one --obvious way to do it.

Try to find one of the best is the only kind of obvious solution.

Python2 in the dictionary can be used to determine whether a key exists has_key method, another way is to use in keywords.

But it is strongly recommended to use the latter, because in the process faster

Another reason is has_key this method was removed in Python3, in order to compatible py2 and py3 two versions of the code, in use is the best choice.

bad

good

2, get the value of the dictionary with get

Get the value on the dictionary, a simple way is to use ** d [x] ** access the element

But this situation does not exist in the case of the key will be reported KeyError wrong, of course, you can first use in the operation to check whether the key and then get in the dictionary,

However, this approach does not meet the Zen of Python in to say:

Simple is better than complex.

Flat is better than nested.

Good code should be straightforward, flat structure more readable code.

We can use the get method instead of if ... else

bad

good

3, the default value is set not in the dictionary with the key setdefault

In doing statistical classification, hoping to return to the same type of data dictionary in a certain type

The above code example, the same type of thing reassembling the form of a list, a new dictionary to obtain

Common way is to first determine whether the key already exists, if there is no list is first initialized with the object, then subsequent operations.

The better way is to use the method setdefault dictionary.

If you are still confused in the programming world, you can join us to learn Python buckle qun: 784758214, look at how seniors are learning. Exchange of experience. From basic web development python script to, reptiles, django, data mining and other projects to combat zero-based data are finishing. Given to every little python partner! Share some learning methods and need to pay attention to small details, click on Join us python learner gathering

bad

good

Setdefault role is to:

  • If the key is present in the dictionary, then directly returns the corresponding value equivalent to the get method
  • If the key does not exist in the dictionary, it will setdefault with the second parameter values ​​of the key, and then returns the value.

4, with a dictionary object initialization defaultdict

If you do not want to D [x] when given in the absence of x, except that the get method in obtaining an element other than

Another way is to use collections module defaultdict

Specify a function to initialize the dictionary when, in fact defaultdict is a subclass of dict.

When the key does not exist in the dictionary, list function is called and returns an empty list is assigned to D [key]

As a result, you do not have to worry about calling d [k] will complain of.

5, the list will be converted into a dictionary with fromkeys

6, to achieve switch ... case statement dictionary

Python does not switch ... case statement

This problem Python turtle t represents the father of this syntax did not and does not, and never will be.

Since Python concise syntax can use if ... elif achieve.

If there are too many branches judge you can also use a dictionary instead.

good

7, using an iterative iteritems element dictionary

python provides several elements of an iterative fashion dictionary, the first method is to use the items:

items method returns a (key, value) list consisting of an object

The drawbacks of this approach is an iterative large dictionary when the moment will be expanded twice the memory, because the list of objects that will be a one-time all the elements loaded into memory

The better way is to use iteritems

iteritems iterator object is returned, iterator object has a characteristic of an inert load

Only when really needed was to generate value, this approach does not require additional memory in an iterative process to load the data.

Note Python3, only items the method, which is equivalent to Python2 in iteritems, and iteritems method name has been removed.

8, using the formula derived dictionaries

Derivation is a wonderful thing, a list of derived type, map, filter functions like eclipsed

Since Python2.7 version, this feature extends to a dictionary and a collection of body

Objects built dictionary dict without calling the method.

bad

good

Guess you like

Origin blog.csdn.net/wcg541/article/details/100086779