"Collections" Data structures and algorithms _ container-type value dictionary & Order Dictionary

Source: Internet
Author: User

First, Collections.defaultdict: multi-valued mapping dictionary

Defaultdict eliminates the process of initializing the container, the default value object is a container of the specified type

You can use the. Append when specifying list.

From collections Import DEFAULTDICTD = Defaultdict (list) d[' a '].append (1) d

Defaultdict (list, {' A ': [1]})

When you specify set, you can use. Add,

D = defaultdict (set) d[' A '].add (1) d[' A '].add (1) d

Defaultdict (set, {' A ': {1}})

The original dictionary can use the. SetDefault method to specify value as a container, but is not recommended, as follows,

D = {}d.setdefault (' a ', []). Append (1) d.setdefault (' A ', []). Append (2) d.setdefault (' B ', []). Append (3) d.setdefault (' C ' , {append}) #默认的dict对象没有add方法, not using the # # because the default method creates a new empty object each time a new element is added [], it is not recommended to D

{' A ': [1, 2], ' B ': [3], ' C ': {1, 2, 3}}

By the way, the content of the dictionary is the key value,

The ' a ' in D # Dictionary in is key

True

Second, collections. Ordereddict: Dictionary with Order

Ordereddict internally maintains a doubly linked list to record the order in which key values are inserted, update the key value does not affect the original order, insert key value is inserted at the end, so its memory consumption is twice times the normal dictionary ,

From collections Import ORDEREDDICTD = Ordereddict () d[' a '] = 1d[' c '] = 3d[' b '] = 2print (d, D.items ())

Ordereddict (' A ', 1), (' C ', 3), (' B ', 2)])

Odict_items (' A ', 1), (' C ', 3), (' B ', 2)])

An ordered dictionary is actually used in conjunction with JSON to output information,

Import json# encode the dictionary and use Orderddict to control the order of the Fields Json.dumps (d)

' {' A ': 1, ' C ': 3, ' B ': 2} '

"Collections" Data structures and algorithms _ container-type value dictionary & Order Dictionary

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.