How to Use the Python dictionary efficiently

Source: Internet
Author: User
Tags case statement

How to Use the Python dictionary efficiently

Preface

As we all know, a dictionary (dict) object is the most commonly used data structure in Python. Some people joke in the community that "Python attempts to load the whole world with a dictionary". The importance of a dictionary in Python is self-evident, I have sorted out several lists of efficient dictionary usage. I hope Python developers can make proper use of them in daily application development to make the code more Pythonic.

1. Use the in keyword to check whether the key exists.

There is a development philosophy in the Zen of Python:

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

Try to find one, preferably the only obvious solution. In Python2, you can use the has_key method to determine whether a key exists in the dictionary. Another method is to use the in keyword. However, we strongly recommend that you use the latter because the in processing speed is faster. Another reason is that the has_key method has been removed from Python3. to be compatible with the code of both py2 and py3 versions, using in is the best choice.

Bad

d = {'name': 'python'}if d.has_key('name'): pass

Good

if 'name' in d: pass

2. Use get to get the value in the dictionary

To obtain the value in the dictionary, you can use d [x] to access this element. However, if the key does not exist, a KeyError is returned, of course, you can first use the in operation to check whether the key is obtained in the dictionary, but this method does not conform to the following in the Python saying:

Simple is better than complex.

Flat is better than nested.

Good code should be easy to understand, and the flat code structure is more readable. We can use the get method to replace if... else

Bad

d = {'name': 'python'}if 'name' in d: print(d['hello'])else: print('default')

Good

print(d.get("name", "default"))

3. Use setdefault to set the default value for the key that does not exist in the dictionary.

data = [  ("animal", "bear"),  ("animal", "duck"),  ("plant", "cactus"),  ("vehicle", "speed boat"),  ("vehicle", "school bus") ]

During classification statistics, we want to classify the data of the same type into a certain type in the dictionary. For example, the code above re-assembles the data of the same type in the form of a list to get a new dictionary.

groups = {}>>> {'plant': ['cactus'],  'animal': ['bear', 'duck'],  'vehicle': ['speed boat', 'school bus']}

The common method is to first determine whether the key already exists. If the key does not exist, first initialize it with the list object and then perform subsequent operations. The better way is to use the setdefault method in the dictionary.

Bad

for (key, value) in data: if key in groups:  groups[key].append(value) else:  groups[key] = [value]

Good

groups = {}for (key, value) in data: groups.setdefault(key, []).append(value)

The role of setdefault is:

  • If the key exists in the dictionary, the corresponding value is directly returned, which is equivalent to the get method.
  • If the key does not exist in the dictionary, the second parameter in setdefault is used as the value of the key and the value is returned.

4. Use defaultdict to initialize the dictionary object

If you do not want d [x] to report an error when x does not exist, in addition to using the get method when getting elements, the other method is to use defaultdict in the collections module, specify a function when initializing the dictionary. In fact, defaultdict is a subclass of dict.

from collections import defaultdictgroups = defaultdict(list)for (key, value) in data: groups[key].append(value)

When the key does not exist in the dictionary, the list function will be called and return an empty list assigned to d [key]. In this way, you do not have to worry about errors when calling d [k.

5. Use fromkeys to convert the list into a dictionary.

keys = {'a', 'e', 'i', 'o', 'u' }value = []d = dict.fromkeys(keys, value)print(d)>>>{'i': [], 'u': [], 'e': [],  'a': [], 'o': []}

6. Implement the switch... case statement using the dictionary

There is no switch... case statement in Python. The father of Python said that this syntax was not used in the past, and it is not used in the future. Because Python's concise syntax can be fully implemented using if... elif. If there are too many branch judgments, you can use dictionaries instead.

if arg == 0: return 'zero'elif arg == 1: return 'one'elif arg == 2: return "two"else: return "nothing"

Good

data = { 0: "zero", 1: "one", 2: "two",}data.get(arg, "nothing")

7. Use iteritems to iterate the elements in the dictionary

Python provides several methods to iterate the elements in the dictionary. The first method is to use the items method:

d = { 0: "zero", 1: "one", 2: "two",}for k, v in d.items(): print(k, v)

The items method returns a list object consisting of (key, value). The disadvantage of this method is that when the dictionary is iterated, the memory will be instantly doubled, because the list object loads all elements to the memory at a time, the better way is to use iteritems

for k, v in d.iteritems(): print(k, v)

Iteritems returns the iterator object. The iterator object has the properties of inert loading and generates values only when needed, this method does not require additional memory to load the data during iteration. Note that in Python3, only the items method is used. It is equivalent to iteritems in Python2, And the iteritems method name is removed.

8. Use dictionary Derivation

Derivation is a wonderful thing. functions such as map and filter are eclipsed by list derivation. In Versions later than Python2.7, this feature is extended to dictionaries and collections, you do not need to call the dict method to build a dictionary object.

Bad

numbers = [1,2,3]d = dict([(number,number*2) for number in numbers])

Good

numbers = [1, 2, 3]d = {number: number * 2 for number in numbers}

Summary

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.