How the list of Python dictionaries is used

Source: Internet
Author: User
This time to bring you a list of Python dictionary How to use, the use of Python dictionary list of considerations, the following is the actual case, together to see.

1. Check if key exists in keyword

There is a development philosophy in the Zen of Python:

There should is one--and preferably only one--obvious the-do it.

Try to find one, preferably the only obvious solution. In Python2, the Has_key method can be used to determine whether a key exists in a dictionary, and the other way is to use the In keyword. However, it is highly recommended to use the latter because of the faster processing of in, and the other reason is that the Has_key method is removed in Python3, to be compatible with both Py2 and py3 two versions of Code, in is the best choice.

badd = {' name ': ' Python '}if d.has_key (' name '):  passgoodif ' name ' in D:  Pass

2. Get the values in the dictionary with get

A simple way to get a value from a dictionary is to use d[x] to access the element, but it will report a keyerror error if the key does not exist, but you can use the in operation to check if the key is in the dictionary again, but this is not what Python says in Zen:

Simple is better than complex.
Flat is better than nested.

Good code should be easy to understand, and a flat code structure is more readable. We can use the Get method instead of if ... else

badd = {' name ': ' Python '}if ' name ' in D:  print (d[' Hello ']) Else:  print (' Default ') Goodprint (D.get ("name", " Default "))

3. Use SetDefault to set default values for keys that do not exist in the dictionary

data = [    ("Animal", "Bear"), ("    Animal", "Duck"), ("    plant", "Cactus"), ("    vehicle", "Speed Boat"    ), ("Vehicle", "school Bus")  ]

When doing categorical statistics, want to classify the same type of data into a dictionary of some type, such as the above code, the same type of things in the form of a list to be reassembled, to get a new dictionary

Groups = {}>>> {' Plant ': [' Cactus '],  ' animal ': [' bear ', ' duck '],  ' vehicle ': [' Speed boat ', ' school Bus ']}

The normal way is to first determine whether the key already exists, if it does not exist, you have to first initialize with the list object, and then perform subsequent operations. The better way is to use the SetDefault method in the dictionary.

Badfor (key, value) in data:  if key in groups:    groups[key].append (value)  else:    Groups[key] = [value] Goodgroups = {}for (key, value) in data:  Groups.setdefault (Key, []). Append (value)

The role of SetDefault is:

If key exists in the dictionary, the corresponding value is returned directly, 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 then the value is returned.

4. Initialize the Dictionary object with Defaultdict

If you do not want d[x] in X, in addition to using the Get method when acquiring an element, another way is to use the defaultdict in the collections module to 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 key does not exist in the dictionary, the list function is called and returns an empty list assignment to D[key], so you don't have to worry about calling D[k] to get an error.

5. Convert the list into a dictionary with Fromkeys

Keys = {' A ', ' e ', ' I ', ' o ', ' u '}value = []d = Dict.fromkeys (keys, value) print (d) >>>{' I ': [], ' u ': [], ' e ': [],
   ' a ': [], ' O ': []}

6. Use a dictionary to implement switch ... case statement

There is no switch in Python ... case statement, the question of the father of Python, Uncle Turtle, said that this grammar has not been, and now does not have. Because Python's concise syntax can be fully implemented with the If ... elif. If there are too many branches to judge, you can also use a dictionary instead.

If arg = = 0:  return ' zero ' elif arg = = 1:  return ' one ' elif arg = = 2: Return "Other"  else:  return "Nothing" good data = {  0: "Zero",  1: "One",  2: "One",}data.get (ARG, "nothing")

7. Using Iteritems to iterate over elements in a dictionary

Python provides several ways to iterate over elements in a dictionary, the first of which is to use the items method:

d = {  0: "Zero",  1: "One",  2: "One",}for K, V in D.items ():  print (k, v)

The items method returns a list object (key, value), the drawback of which is that when iterating over a large dictionary, memory instantly expands by twice times, because the list object loads all the elements into memory at once, and the better way is to use Iteritems

For K, V in D.iteritems ():  print (k, v)

Iteritems returns an Iterator object that has an inert loading feature that generates values only when it is really needed, which does not require additional memory to mount the data during the iteration. Note that in Python3, only the items method, which is equivalent to Iteritems in Python2, is removed from the Iteritems method name.

8. Using Dictionary derivation formula

Derivation is a wonderful thing, list derivation, map, filter and other functions are eclipsed, since Python2.7 version, this feature extends to the dictionary and collection Body, building a Dictionary object without calling the Dict method.

Badnumbers = [1,2,3]d = Dict ([(number,number*2) for number in numbers]) goodnumbers = [1, 2, 3]d = {Number:number * 2 for Number in Numbers}

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:

How to convert matrices to lists in Python

A summary of how Python connects to MySQL

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.