Type python - Dictionary

Python language dictionary is the only type of mapping, mapping object Li Haxi value (key, key) and pointed objects (value, value) is one to many relationship. A dictionary object is variable, is a container type, can be any number of objects stored python, which may also include other types of containers.

1. Create a dictionary and a dictionary assignment

Just need to create a dictionary field assignment to a variable, regardless of whether the dictionary contains an element.

>>> dict1 = {}

>>> dict2 = {'name':'earth', 'port':80}

Or use the factory method dict () to create a dictionary.

>>> fdict = dict((['x', 1], ['y', 2]))

>>> fdict

{ 'And' 2, 'x': 1}

Further methods using the built fromkeys () to create a "default" dictionary, the dictionary elements have the same value (if not given, the default is None)

>>> ddict = {}.fromkeys(('x', 'y'), -1)

>>> ddict

{ 'And' -1 'x': -1}

>>> edict = {}.fromkeys(('foo', 'bar'))

>>> edict

{'foo': None, 'bar': None}

2. The value of access to the dictionary

Traversing a dictionary (usually with key), we only need to cycle through its key

>>> dict2 = {'name':'foo', 'port':80}

>>> for key in dict2.keys():

... print 'key:%s value:%s' % (key, dict2[key])

...

key:name value:foo

key:port value:80

Also available iterates class sequence object (sequence-like objects), such as dictionaries and file, just use the name of the dictionary you can traverse the dictionary for loop.

>>> dict2 = {'name':'foo', 'port':80}

>>> for key in dict2:

... print 'key:%s value:%s' % (key, dict2[key])

...

key:name value:foo

key:port value:80

Need to get the value of an element of the dictionary, the dictionary key plus the brackets get.

>>> dict2 = {'name':'foo', 'port':80}

>>> dict2['name']

'foo'

3. Update dictionary

There are the following ways: add a new item or a new data element (ie, a key - value pairs); the data item to modify an existing; delete a data item that already exists.

>>> dict2 = {'name':'foo', 'port':80}

>>> dict2['name'] = 'jone'

>>> dict2['arch'] = 6969

>>> dict2

{'arch': 6969, 'name': 'jone', 'port': 80}

>>> del dict2['name']

>>> dict2

{'arch': 6969, 'port': 80}

>>> dict2.clear()

>>> dict2

{}

>>> del dict2

>>> dict2

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'dict2' is not defined

>>> dict2 = {'name':'foo', 'port':80}

>>> dict2.pop ( 'name') # remove and return key to "name" entry

'foo'

>>> dict2

{'port': 80}

4. The dictionary key

A plurality of allowed values ​​corresponding to a key: the key corresponding to a plurality of values ​​is not allowed (such as a list of containers, dictionaries and other tuples are possible). When a key is in conflict (i.e., repeated key assignment dictionary), taking the final assignment;

Hash keys must be: All types are immutable hashable, the same numerals the same key value (e.g., 1.0 and 1).

The type of mapping operator

5.1. Operators standard type

=、<、>、and

5.2. Dictionary lookup key operator ([])

Key for the dictionary lookup operator only type of operator, the query with the key, the key is a parameter

d [k] = v by the key "k", assigned to an element in the dictionary "v"

d [k] by the key "k", the value of an element query dictionary.

5.3. (Key) membership operation (in, not in)

Similar has_key () method

>>> 'name' in dict2

True

6. The built-in functions and the mapping type factory function

6.1 Standard function type (type (), str () and cmp ())

type (): dictionary call type () factory method that returns a dictionary "<type 'dict'>"

str (): Returns a string representation of the dictionary

cmp (): First, compare the size of the dictionary, then the key, and finally the value.

6.2. Mapping type correlation function

dict (): used to create the dictionary, if the parameter is not available, generating empty dictionary; if the parameter is iterative (a sequence, or an iterator object or support iteration), and that each element must be iterative to to appear. Value in each pair, the first element is a dictionary key, the second element is the value of the dictionary.

>>> dict()

{}

>>> dict([['x', 1], ['y', 2]])

{ 'And' 2, 'x': 1}

>>> dict([('xy'[i-1], i) for i in range(1,3)])

{ 'And' 2, 'x': 1}

len (): Use dictionary len () returns all of the elements - the number (key value pairs)

>>> dict2 = {'a':1, 'b':2}

>>> len(dict2)

2

hash (): determine whether an object can be used as a dictionary key, an object is passed as a parameter to hah (), returns the hash value of the object, the object is only the hash, it can be used as a dictionary key .

>>> hash([])

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: unhashable type: 'list'

>>> hash(())

3527539

6.3 Mapping type built-in methods

keys (): returns a list containing all of the dictionary keys;

values ​​(): returns a list containing all the values ​​in the dictionary;

items (): returns a all - list (key value) tuple.

sorted():

{'a': 1, 'c': 2, 'b': 3}

>>> for ek in sorted(dict1):

... print 'key:', ek, 'value:', dict1 [ek]

...

key: a value: 1

key: b value: 3

key: c value: 2

update (): add the contents of a dictionary to another dictionary, the dictionary if any original bond was repeated adding new key, then the duplicate key corresponding to the original entry will be the new key value corresponding to the coverage.

>>> dict1

{'a': 1, 'c': 2, 'b': 3}

>>> dict2 = {'b':3, 'd':5}

>>> dict1.update(dict2)

>>> dict1

{'a': 1, 'c': 2, 'b': 3, 'd': 5}

>>>

() Copy: Returns a copy of the dictionary, shallow copy.

setdefault (): Check whether the dictionary contains a key, if the key exists in the dictionary, it can take the value, if the key does not exist in the dictionary, this key can be assigned to the default value and this value is returned.

>>> mdict = {'host':'zheng', 'port':80}

>>> mdict.setdefault('prot', 'tcp')

'tcp'

>>> mdict.setdefault('port', '8080')

80

>>> mdict.items()

[('host', 'zheng'), ('prot', 'tcp'), ('port', 80)]

>>>

Appendix: Mapping type built-in methods

Method name

operating

dict.clear()

Delete all the elements in the dictionary

dict.copy()

Return Dictionary (shallow copy) a copy of the

dict.fromkeys(seq, val=None)

Creates and returns a new dictionary to seq in the dictionary as a key element, val as all keys corresponding to the initial value of the dictionary, if this value is not provided, the default is None

dict.get(key, default=None)

Dict key in the dictionary key, returns a value corresponding to its value, if the key does not exist in the dictionary, the default value is returned (default parameter default None)

dict.has_key(key)

If the key exists in the dictionary, it returns True, otherwise it returns False, equivalent to in, not in operators

dict.items()

Returns a dictionary comprising key, a list of tuples of values

dict.keys()

It returns a list containing the keys in the dictionary

DICT.ITER ()

Methods iteritems (), iterkeys (), itervalues ​​() method as with their corresponding non-iterative, except that they return a sub-iteration, rather than a list

dict.pop(key[, default])

And get () method similar to, if the dictionary key key exists, and returns the delete dict [key], key if the key does not exist, and the default value is not given, the exception is thrown KeyError

dict.setdefault(key, default=None)

Method and set () is similar, but the key if the key does not exist in the dictionary, by dict [key] = default assignment for it

dict.update(dict2)

The dictionary dict2 of key-value pairs added to the dictionary dict

dict.values()

It returns a list of all the values ​​contained in the dictionary

Guess you like

Origin www.cnblogs.com/mrlayfolk/p/11980224.html