The use and difference of Python collections.defaultdict () and Dict

Source: Internet
Author: User

It seems that this document is difficult to read. Look directly at the example:

123456789101112131415161718 importcollections=[(‘yellow‘1), (‘blue‘2), (‘yellow‘3), (‘blue‘4), (‘red‘1)]# defaultdict=collections.defaultdict(list)for k, v ins:    d[k].append(v)# Use dict and setdefault   ={}fork, v ins:    g.setdefault(k, []).append(v)     # Use dict={}fork, v ins:    e[k] =v##list(d.items())##list(g.items())##list(e.items())

Look at the results

12345678910111213141516171819202122 list(d.items())[(‘blue‘, [24]), (‘red‘, [1]), (‘yellow‘, [13])]>>> list(g.items())[(‘blue‘, [24]), (‘red‘, [1]), (‘yellow‘, [13])]>>> list(e.items())[(‘blue‘4), (‘red‘1), (‘yellow‘3)]>>> ddefaultdict(<class‘list‘>, {‘blue‘: [24], ‘red‘: [1], ‘yellow‘: [13]})>>> g{‘blue‘: [24], ‘red‘: [1], ‘yellow‘: [13]}>>> e{‘blue‘4‘red‘1‘yellow‘3}>>> d.items()dict_items([(‘blue‘, [24]), (‘red‘, [1]), (‘yellow‘, [13])])>>> d["blue"][24]>>> d.keys()dict_keys([‘blue‘‘red‘‘yellow‘])>>> d.default_factory<class‘list‘>>>> d.values()dict_values([[24], [1], [13]])

Can see

Collections.defaultdict (list) uses the same effect as using Dict.setdefault ().

That's what Python help says.

When each key was encountered for the first time, it was not already in the mapping; So a entry is automatically created using the Default_factory function which returns an empty list. The List.append () operation then attaches the value to the new list. When Keys is encountered again, the look-up proceeds normally (returning the list for that key) and the List.append () ope Ration adds another value to the list. This technique are simpler and faster than an equivalent technique using Dict.setdefault ():

This method is equivalent to Dict.setdefault (), but faster.

It is necessary to see Dict.setdefault ()

SetDefault (key[, default])

If key is in the dictionary, return its value. If not, insert key with a value of default and return default. Default defaults to None.

If the key is already stored in the dictionary, return value. If key does not exist, insert key and a default value to return to default. The default defaults is None.

However, it is important to note that defaultdict is equivalent to Dict.setdefault, which is different from the direct assignment below. As you can see from the results, the direct assignment is overwritten.

From the last d.values and d["Blue"], the use of the latter is actually the same as the usage of dict, the only difference is the problem of initialization. Defaultdict can use the factory function to bring a default value to the initial keyi.

This default value may be empty list[] defaultdict (list), perhaps 0, defaultdict (int).

Take a look at the following example.

defaultdict (int) The d here actually generates a data dictionary with key that defaults to 0. You can imagine it as d[key] = int default (the value of the Int factory function is 0)

D[k] So can be read directly d["M"] + = 1 is d["M"] is the default value 0+1 = 1

The reason behind it is the same.

1234567 >>> s =‘mississippi‘>>> d = defaultdict(int)>>> forins:...     d[k] +=1...>>> list(d.items())[(‘i‘4), (‘p‘2), (‘s‘4), (‘m‘1)]

The use and difference of Python collections.defaultdict () and Dict

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.