Python Dictionaries and collections

Source: Internet
Author: User

Dictionary

Creation of dictionaries

>>> A = {' One': 1,' Both': 2,'three': 3}>>> B = dict (one=1, two=2, three=3)>>> C = Dict ([(' Both', 2), (' One', 1), ('three', 3)])>>> A = = b = =ctrue>>> d = {}.fromkeys ('x','y'), 1)>>>d{'y': 1,'x': 1}

Accessing values in a dictionary

d[key]d.get (Key) D.items (), D.keys (), D.values () D.iteritems (), D.iterkeys (), d.itervalues () ' x ' inch dtrue

Update dictionary

>>> d['x'] = 2#Update>>> d['Z'] = 2#Insert>>> D2 = Dict (one=1, two=2)>>> d3 = Dict (one=10, ten=100)>>>D2.update (D3)>>>d2{' Both': 2,'Ten': 100,' One': 10}

Delete a dictionary element

del d[key]d.pop (key[, default]) D.clear ()

Copy Dictionary

D.copy ()   #  Note is a shallow copy

Collection

A collection (sets) has two different types, a mutable set (set), and an immutable set (Frozenset).
For mutable collections (set), you can add and remove elements, which are not allowed for immutable collections (Frozenset).

Create a Collection

 >>> t = Set ( " hello  "   >>> Tset ([ "  h  , "   ,    L  ,    o  ]) #   >>> set ([1, 2, 3, 4, 1, 2 1, 2, 3, 4])  

Accessing values in a collection

' H ' inch ttrue  for inch T:         Print I

Operation of the collection

A = T | The intersection of S          #  T and S-B = t & S # T and s, C =              t–s #              Differential set (item in T, but not in s)  d = t ^ s          #  symmetric difference set (items in t or S, but not both)

Update Collection

>>> T.add ('m')>>>Tset (['H','m','e','L','o'])>>> T.update (' World')>>>Tset (['e','D','H','m','L','o','R','W'])>>> T.remove ('m')>>>Tset (['e','D','H','L','o','R','W'])>>> T-= set (' World')>>>Tset (['e','H'])

PS: The collection can be used to list the weight

 for  in Set ([11,22,33,44,11,22]) [33, 11, 44, 22]  

2015-05-26

Python Dictionaries and collections

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.