Summary of the usage of python dictionary operations

Source: Internet
Author: User
Tags dota
This article describes in detail the usage of python dictionary operations. For more information, see

Basic syntax:

Dict = {'ob1': 'computer ', 'ob2': 'Mouse', 'ob3': 'printer '}

Tips:

The dictionary contains the list: dict = {'angrong ': ['23', 'It'], "xiaohei": ['22', 'Dota']}.

The dictionary contains the following dictionaries: dict = {'hangzhou': {"age": "23", "job": "IT"}, "xiaohei": {"'age ': '22', 'job': 'Dota '"}}

Available commands:

Root @ yangrong :~ # Cd/python

Root @ yangrong:/python # python

Python 2.7.5 + (default, Sep 19 maid: 48: 49)

[GCC 4.8.1] on linux2

Type "help", "copyright", "credits" or "license" for moreinformation.

>>> Import tab

>>> D = {}

>>> D.

D. class (d. ge (d. len (d. setitem (d. has_key (d. setdefault (

D. cmp (d. getattribute (d. lt (d. sizeof (d. items (d. update (

D. contains (d. getitem (d. ne (d. str (d. iteritems (d. values (

D. delattr (d. gt (d. new (d. subclasshook (d. iterkeys (d. viewitems (

D. delitem (d. hash d. reduce (d. clear (d. itervalues (d. viewkeys (

D.doc d. init (d. performance_ex (d. copy (d. keys (d. viewvalues (

D. eq (d. iter (d. repr (d. fromkeys (d. pop (

D. format (d. le (d. setattr (d. get (d. popitem (

>>> D.

Add dictionary elements

>>> Nameinfo = {}

>>> Nameinfo ['A1'] = 'yangrong '# if the dictionary contains an a1 primary key, it overwrites the original value. If no, it is added.

>>> Nameinfo

{'A1': 'yangrong '}

Traverse dictionary primary keys and key values

>>> For k, value innameinfo. items ():

... Print k, value

...

A1 yangrong

View all primary keys in the dictionary

>>> Dict = {'ob1': 'computer ', 'ob2': 'Mouse', 'ob3': 'printer '}

>>>

>>>

>>> Dict. keys ()

['Ob2', 'ob3', 'ob1']

Determines whether the primary key exists in the dictionary.

>>> Dict. keys ()

['Ob2', 'ob3', 'ob1']

>>> Dict. has_key ('ob2') # or 'ob2' in dict

True

>>> Dict. has_key ('ob4 ')

False

Some people use the loop method to judge

For key in dict. keys ():

However, this method is not concise,

View all Dictionary key values

>>> Dict = {'ob1': 'computer ', 'ob2': 'Mouse', 'ob3': 'printer '}

>>> Dict. values ()

['Mouse ', 'printer', 'computer ']

List all projects

>>> Dict. items ()

[('Ob2', 'mouse '), ('ob3', 'printer'), ('ob1', 'computer')]

Clear dictionary

>>> Dict. clear ()

>>> Dict

{}

Copy Dictionary

>>> Dict

{'Ob2': 'Mouse ', 'ob3': 'printer', 'ob1': 'computer '}

>>> A = dict

>>>

{'Ob2': 'Mouse ', 'ob3': 'printer', 'ob1': 'computer '}

>>> B = dict. copy ()

>>> B

{'Ob2': 'Mouse ', 'ob3': 'printer', 'ob1': 'computer '}

Comparison Dictionary

>>> Cmp (a, B)

First, compare the length of the primary key, then compare the size of the key, and then compare the size of the key value (the first large returns 1, small returns-1, returns 0)

Update Dictionary

>>> Dict = {'yangrong ': {"age": "23", "job": "IT"}, "xiaohei": {"'age ': '22', 'job': 'Dota '"}}

>>> Dict

{'Xiaohei': set (["'age': '22', 'job': 'Dota '"]), 'yangrong': {'age ': '23', 'job': 'It '}}

>>> Dict ['xiaohei'] = 111 # Modify the first-level Dictionary

>>> Dict

{'Xiaohei': 111, 'hangzhou': {'age': '23', 'job': 'It '}}

>>> Dict ['yangrong '] ['age'] = 25 # Modify a secondary dictionary

>>> Dict

{'Xiaohei': 111, 'hangzhou': {'age': 25, 'job': 'It '}}

>>> Dict = {'yangrong ': ['23', 'It'], "xiaohei": ['22', 'Dota']}

>>> Dict ['xiaohei'] [1] = "dota2" # modify an item in the dictionary list. 1 represents the 2nd strings in the list.

>>> Dict

{'Xiaohei': ['22', 'dota2'], 'angrong ': ['23', 'It']}

Delete dictionary elements

>>> Dict

{'Xiaohei': ['22', 'dota2'], 'angrong ': ['23', 'It']}

>>> Del dict ['xiaohei'] # Delete the xiaohei key value

>>> Dict

{'Yangrong ': ['23', 'It']}

>>> Dict

{'Yangrong ': ['23', 'It']}

>>>

>>> Del dict ['yangrong '] [1] # delete every 2-word value of the yangrong primary key

>>> Dict

{'Yangrong ': ['23']}

Delete the entire dictionary

>>> Dict

{'Yangrong ': ['23']}

>>> Dict. clear () # Same as del dict

>>> Dict

{}

Split string into a list

>>> S = "hello world bye"

>>> S. split () # used to read regular text, modify the list, and then write the file.

['Hello', 'World', 'bye']

Converts a list to a string.

S. split (str, '') # Convert string to list and split with spaces

Storage Dictionary (pickle serialization)

# Import the pickle module import pickle

Store dictionary content into a file

F=file('data.txt ', 'WB') when a new file data.txt, 'WB ', and B is used to open a block file.

Pickle. dump (a, f) # serialize a to a file

F. close ()

Read the content into the dictionary (deserialization)

Aw.open('data.txt ', 'RB') # open the file

Print pickle. load (a) # deserialize all content

The above is a summary of the usage of the python dictionary. For more information, see other related articles in the first PHP community!

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.