Python Basics: Dictionary dict

Source: Internet
Author: User
Tags delete key shallow copy

Attention:

# Dictionary is a mutable type
# The data in the dictionary is unordered
# The syntax of a dictionary entry is a key: value
# Any immutable data type can be a key to an entry

Knowledge Point one: Create

Key: Must be unique (if the key is repeatedly deposited, will be overwritten), can only be immutable type (commonly used strings and numbers)
Value: Can be any data type

Knowledge Point two: Accessing Data items

Via key------Dic[key]
If key does not exist, Keyerror is not indexed! No shards!

Knowledge Point Three: updating data items

Dic[key] = value If key does not exist, it is a new data item

Knowledge Point Four: deleting data items

Del Dic[key] Delete key is ' key ' entry
Del dict Delete Dictionary

Knowledge Point Five: dictionary method

Determine if key exists
*has_key (Key)
*in, not in

*dict.keys () Returns a list containing all keys for the dictionary

*dict.values () Returns a list containing all the value of the dictionary

*dict.items () Returns a list that contains all (key, value) Ganso

Dic.pop (key) deletes the key keys and returns the value corresponding to key, if key does not exist, an error

Dict.clear () Delete all items or elements in the dictionary

Dict.copy () Returns a copy of a shallow copy of a dictionary

*dict.fromkeys (seq, val=none) creates and returns a new dictionary that is the key to the dictionary in the SEQ element, and Val does the initial value for all the keys in the dictionary (default is None)

Dict.get (key, Default=none) returns the value of key in the dictionary, and returns the value of default if the key does not exist in the dictionary (default defaults to None)

*adict.update (bdict) adds a dictionary bdict key-value pair to the dictionary adict
Key exists, the value is updated. Key does not exist for new data items.

Dictionary Merge Update

Knowledge Point Six: Operations

The dictionary does not support splicing and repeating operators (+,*)
Dictionary comparison operations: length, key, etc., value, etc.

Knowledge Point seven: iteration

Traversing the Dictionary key
For key in Adict.keys ():p rint key

Iterate through the value of a dictionary
For value in Adict.values (): Print value

To traverse a dictionary item
For item in Adict.items ():p rint Item

Traversing the key-value of a dictionary
For key, value in Adict.items (): print ' key=%s, value=%s '% (key, value)

* iterators
The ITER () function can iterate an object into an iterator
The iterator has a next () method that returns the next item, and throws a stopiteration error when there is no value
Dict.iteritems (), Dict.iterkeys (), Dict.itervalues ()
As with the non-iterative methods they correspond to, the difference is that they return an iteration rather than a list;

Knowledge Point eight: sort

Sorted (Dic,value,reverse)

DIC is an object that can be iterated, and value is a sorted object (here a key or a key value)
Reverse: Indicate ascending or descending, true--descending, false--ascending (default)
Key sort
--sorted (Dict.keys ())
--sorted (Dict.items (), Key=lambda item:item[0])
Value sort
--sorted (Dict.values ())
--sorted (Dict.items (), Key=lambda item:item[1])

*collections:ordereddict
Ordereddict keys are sorted in the order in which they are inserted, not the key itself.

Knowledge Point nine: type conversion

Other types of Turn dictionaries:
String: eval (str)
List:
Two-dimensional list conversion
Manual construction
Using zip

Dictionary goto list:
List (dic) = = Dict.keys ()
Dict.keys () dict.values ()
Dictionary transfer tuple:
Tuple (DIC)--Contains only key values
Dictionary to string:
STR (DIC)

practice One: Put the string "K1:1|k2:2|k3:3" processed into python the form of a dictionary : {' K3 ': 3, ' K2 ': 2, ' K1 ': 1

string = "K1:1|k2:2|k3:3"
dic={}
Print String.Split ("|")
For KV in String.Split ("|"):
K,v =kv.split (":")
If V.isdigit ():
V=int (v)
Dic[k]=v
Print dic

Exercise two:

Python Basics: Dictionary 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.