Dictionary Learning notes in python

Source: Internet
Author: User
Tags python list in python

A dictionary is a sequence structure that is most similar to a php array. The python list can only start with an index number and increase sequentially. The dictionary can be a sequence of letters as the key.

Tuples are generally represented by parentheses, such as (, 3)
The list is usually represented by square brackets, such as [1, 2, 3].
The dictionary (dict) is represented by braces, such as {'a': 1, 'B': 2, 'C': 3}
Unlike php, the key and value of php are expressed by key => value, while python is separated by the colon.

You can use braces to write keys and values or use the dict function to create a dictionary.
The dict function can specify two tuples or lists to create a dictionary. For example:
Items = [('name', 'Gumby'), ('age', '42')]
D = dict (items)
Differences from the list:
K in d (d is a dictionary), which searches for keys rather than values. The expression v in l (l is a list) is used to find values rather than indexes.

Some dictionary methods:

Clear the dictionary. "In-situ operation" does not return values, similar to the sort method of the list
The copy method returns a new dictionary with the same key-value pair. Shortest replication. Because the value itself is the same, not the copy.
When the value is replaced in the copy, the original dictionary is not affected. However, if a value is modified, the original dictionary also changes. One way to avoid this problem is to use deep copy ).
From copy import deepcopy
Deepcopy (d)

D. The fromkes method uses the given value to create a new dictionary. By default, each key corresponds to None.
When the get method gets a key that does not exist, no error is reported and None is returned.
The has_key method is used in the expression k in d.
The items method returns all letter items in the form of a list. Each item in these lists comes from (key, value ). However, there is no special order for items to be returned.
The iteritmes method is roughly the same, but an iterator object instead of a list is returned. In many cases, iteritems is more efficient. Iterator, which is equivalent to an object after decode json, rather than an array,
The keys method returns the keys in the dictionary as a list. Iterkeys returns the iterator for the key.
Pop pops up the value of the given key. Popitem will pop up the last element (actually a random item), but if you want to remove and process the dictionary one by one, the popitem efficiency will be much higher, because it is not necessary to obtain the dictionary key value list first.

The values and itervalues methods return the value in the dictionary in the form of a list or iterator. The returned value list can contain repeated items.


Built-in data types

1. Dictionary is a built-in data type that defines the one-to-one relationship between keys and values. Similar to hashtable instances in java, it is unordered and key is case sensitive.
Unlike java, Keys can only be strings, integers, or basic types, and values can be values of different data types,
Del can delete elements with key and clear
Keys returns the key list, the list returned by values, items () returns a dictionary tuple
2. List: more like an array in java, ArrayList
You can use a negative index to start counting forward from the end of the list.
Use a [1: n] to implement list sharding.
Directly append the elements to the end of the team, add the elements to the insert (pos, obj) in the pos, and connect the extend to the list.
Directly use index to find the position of the element in the list. If it is not found, an exception is thrown. You can use in to determine whether the element is in the list.
Directly use remove to delete an element. You can use pop to obtain and delete a later element.
The * operator can be used as the repeater for list. [1, 2] * 3 = [1, 2, 1, 2]
A simple method is to apply a function to each element in the list and map it to another list.
Li = [1, 2, 4]
[Elem * 2 for elem in li]
[2, 4, 6, 8]
3. Tuple: an unchangeable list. tuple can be used as the key of a dictionary.
Tuple can be used to assign multiple values at a time.

4. Variables are not defined. The first value assignment is generated. When the value exceeds the scope, the variable automatically disappears.
Variable value assignment can be a branch and used as a line feed.
You cannot use a variable without a value.
5. range can be used to return a list of integers.
6. python supports formatting strings and inserting a value at % s.
"String template contains % s" % (params );
% D indicates an integer, % f indicates a floating point number (6 decimal places), and %. 2f indicates two decimal places, % +. 2f indicates print positive and negative

7. ";". join (list) use ";" to connect the elements in the list
String. split (";") is used to separate strings.

1.1 create a dictionary

Python has two ways to create a dictionary. The first is to use curly brackets, and the other is to use the built-in function dict.

>>> Info = {}
>>> Info = dict ()
1.2 initialize the dictionary
Python can initialize a dictionary when creating a dictionary.

>>> Info = {"name": 'cold '}
>>> Info = dict (name = 'cold') # More elegant
Obviously, the second method is more elegant and reduces the input of some special characters, but in some cases, the second method is not competent.

>>> Key = 'name'
>>> Info = {key: 'cold' }# {'name': 'cold '}
>>> Info = dict (key = 'cold') # {'key': 'cold '}

Obviously, the second method will cause a bug that is not easy to find.

Another initialization method is to use the fromkeys method of the dictionary to obtain elements from the list as keys and initialize them with the second parameter of the None or fromkeys method.

>>> Info ={}. fromkeys (['name', 'blog '])
>>> Info
{'Blog ': None, 'name': None}
>>> Info = dict (). fromkeys (['name', 'blog '])
>>> Info
{'Blog ': None, 'name': None}
>>> Info = dict (). fromkeys (['name', 'blog '], '111cn. Net ')
>>> Info
{'Blog ': '111cn. Net', 'name': '111cn. Net '}

1.3 elegant key value acquisition

The dictionary can obtain the key value in this way.

>>> Info = {'name': 'cold', 'blog ': '111cn. Net '}
>>> Info ['name']
'Cold'

However, if a key that does not exist is obtained, a KeyError exception is triggered. The dictionary has a get Method. You can use the dictionary get method to obtain the dictionary more elegantly.

>>> Info = dict (name = 'cold', blog = 'www .111cn.net ')
>>> Info. get ('name ')
'Cold'
>>> Info. get ('blogname ')
None
>>> Info. get ('blogname', 'linuxzen ')
'Linuxzn'

We can see that the get method does not trigger an exception when obtaining a nonexistent key value. At the same time, the get method receives two parameters, if this key does not exist, the second parameter value is returned. We can see that get is more elegant.

1.4 update/add

The Python dictionary can use keys as indexes to access, update, and add values.

>>> Info = dict ()
>>> Info ['name'] = 'cold'
>>> Info ['blog '] = '111cn. Net'
>>> Info
{'Blog ': '111cn. Net', 'name': 'cold '}
>>> Info
{'Blog ': '111cn. Net', 'name': 'Cold night '}

The update method of the Python dictionary can also be used to update and add a dictionary.

>>> Info = dict (name = 'cold', blog = '111cn. Net ')
>>> Info. update ({'name': 'Cold night ', 'blogname': 'linuxzen '})
>>> Info
{'Blog ': '111cn. Net', 'name': 'Cold night', 'blogname': 'linuxzen '}
>>> Info. update (name = 'cold', blog = 'www .111cn.net ') # More elegant
>>> Info
{'Blog ': 'www .111cn.net', 'name': 'cold', 'blogname': 'linuxzen '}

The update method of the Python dictionary can use a dictionary to update the dictionary. You can also use parameters to pass the same method as the dict function to update a dictionary. The second feature in the above code is more elegant, however, similar to dict functions, when a key is a variable, only the literal value is used.

1.5 delete a dictionary

You can call the built-in Python keyword del to delete a key value.

>>> Info = dict (name = 'cold', blog = '111cn. Net ')
>>> Info
{'Blog ': '111cn. Net', 'name': 'cold '}
>>> Del info ['name']
>>> Info
{'Blog ': '111cn. Net '}

You can also use the pop method of the dictionary to retrieve a key value and delete it.

>>> Info = dict (name = 'cold', blog = '111cn. Net ')
>>> Info. pop ('name ')
'Cold'
>>> Info
{'Blog ': '111cn. Net '}

1.6 Other operations

Get all keys

>>> Info = dict (name = 'cold', blog = '111cn. Net ')
>>> Info. keys ()
['Blog ', 'name']

Get key, value and loop

>>> Info = dict (name = 'cold', blog = '111cn. Net ')
>>> For key, value in info. items ():
... Print key, ':', value
...
Blog: 111cn.net
Name: cold

Method 1:

>>> Dict1 = {}
>>> Dict2 = {'name': 'Earth ', 'port': 80}
>>> Dict1 and dict2
({},{ 'Port': 80, 'name': 'global '})

Method 2: From Python 2.2, you can use a Factory method to input a list of tuples as parameters.

>>> Fdict = dict (['X', 1], ['y', 2])
>>> Fdict
{'Y': 2, 'x': 1}

Method 3:

From Python 2.3, you can use fromkeys (), a convenient built-in method, to create a "default" Dictionary. The elements in the dictionary have the same value (if not given, the default value is None, which is a bit like the oneObject method of my framework ):

>>> Ddict ={}. fromkeys ('X', 'y'),-1)
>>> Ddict
{'Y':-1, 'x':-1}
>>>
>>> Edict ={}. fromkeys ('foo', 'bar '))
>>> Edict
{'Foo': None, 'bar': None}

Value in the access Dictionary

To traverse a dictionary (usually using a key), you only need to view its key cyclically, as shown in the following code:

>>> Dict2 = {'name': 'Earth ', 'port': 80}
>>>
>>>> For key in dict2.keys ():
... Print 'key = % s, value = % s' % (key, dict2 [key])
...
Key = name, value = earth
Key = port, value = 80

From Python 2.2, you can traverse the dictionary directly in the for loop.

>>> Dict2 = {'name': 'Earth ', 'port': 80}
>>>
>>>> For key in dict2:
... Print 'key = % s, value = % s' % (key, dict2 [key])
...
Key = name, value = earth
Key = port, value = 80

To determine whether a key-value pair exists, you can use the has_key () or in or not in operators.

>>> 'Server' in dict2 # or dict2.has _ key ('server ')
False
>>> 'Name' in dict # or dict2.has _ key ('name ')
True
>>> Dict2 ['name']
'Global'

An example of mixing numbers and strings in a dictionary:

>>> Dict3 = {}
>>> Dict3 [1] = 'abc'
>>> Dict3 ['1'] = 3.14159
>>> Dict3 [3.2] = 'XYZ'
>>> Dict3
{3.2: 'XYZ', 1: 'ABC', '1': 3.14159}

Update Dictionary

Update by overwriting

In the preceding example, dict2 ['name'] = 'global ';

Update dict2 ['name'] = 'abc ';

Delete dictionary elements and dictionaries

Del dict2 ['name'] # Delete an entry whose key is "name"

Dict2.clear () # Delete all entries in dict2

Del dict2 # delete the entire dict2 Dictionary

Dict2.pop ('name') # Delete and return an entry whose key is "name"

Dict2 = {'name': 'Earth', 'port': 80}
>>> Dict2.keys ()
['Port', 'name']
>>>
>>> Dict2.values ()
[80, 'global']
>>>
>>> Dict2.items ()
[('Port', 80), ('name', 'global')]
>>>
>>> For eachKey in dict2.keys ():
... Print 'dict2 key', eachKey, 'has value', dict2 [eachKey]
...
Dict2 key port has value 80
Dict2 key name has value earth

The update () method can be used to add the content of a dictionary to another dictionary.


Dict3 = {'server': 'http', 'port': 80, 'host': 'Venus '}
>>> Dict3.clear ()
>>> Dict3
{}

Ing type related functions

>>> Dict (x = 1, y = 2)
{'Y': 2, 'x': 1}
>>> Dict8 = dict (x = 1, y = 2)
>>> Dict8
{'Y': 2, 'x': 1}
>>> Dict9 = dict (** dict8)
>>> Dict9
{'Y': 2, 'x': 1}

Dict9 = dict8.copy ()

Dictionary built-in method

Method name Operation
Dict. clear () Delete all elements in the dictionary
Dict. copy () Returns a copy of the dictionary.
Dict. fromkeysc (seq, val = None) Create and return a new dictionary. Use the elements in seq as the dictionary key, and val as the initial values corresponding to all keys in the dictionary (if this value is not provided, the default value is None)
Dict. get (key, default = None) Returns the value corresponding to the key in the dictionary dict. If the key does not exist in the dictionary, the default value is returned (note that the default value of the parameter is None)
Dict. has_key (key) If the key exists in the dictionary, True is returned; otherwise, False is returned. after the in and not in methods are introduced in Python2.2, this method is almost obsolete, but a working interface is still provided.
Dict. items () Returns a list of tuples containing Dictionary (key, value) pairs.
Dict. keys () Returns a list of dictionary types.
Dict. values () Returns a list containing all values in the dictionary.
Dict. iter () Methods iteritems (), iterkeys (), and itervalues () are the same as their non-iterative methods. The difference is that they return an iterator instead of a list.
Dict. pop (key [, default]) Similar to the get () method, if the key in the dictionary exists, delete it and return the dict [key]. If the key does not exist and no default value is given, a KeyError exception is thrown.
Dict. setdefault (key, default = None) Similar to the method set (), if the dictionary does not contain a key, the value is assigned by dict [key] = default.
Dict. setdefault (key, default = None) Similar to the method set (), if the dictionary does not contain a key, the value is assigned by dict [key] = default.

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.