Python study notes -Python Dictionary (Dictionary)

Each dictionary key key => value of the colon  :  split, between each key pair with a comma, segmentation , the whole dictionary includes in braces {} in the following format:

d = {key1 : value1, key2 : value2 }

Generally unique key, if the last repetition of a key-value replaces the preceding value need not be unique .

>>>dict = {'a': 1, 'b': 2, 'b': '3'}
>>> dict['b']
'3'
>>> dict
{'a': 1, 'b': '3'}

Type of data may take any value

A simple example dictionary:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

So also create a dictionary:

dict1 = { 'abc': 456 } dict2 = { 'abc': 123, 98.6: 37 }


Access the dictionary values

The corresponding key in square brackets , the following examples:

Examples

#!/usr/bin/python
 
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
 
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']

Examples of the above output:

dict['Name']:  Zara
dict['Age']:  7

If there are no keys to access the data dictionary, it will output an error KeyError


Modifying a dictionary

Way to add new content to the dictionary to add new key / value pairs, modify, or delete existing key / value pairs in the following examples:

Examples

#!/usr/bin/python
 
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
 
dict['Age'] = 8 # 更新
dict['School'] = "RUNOOB" # 添加
 
 
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']

Examples of the above output:

dict['Age']:  8
dict['School']:  RUNOOB

Delete dictionary elements

Can delete a single element can be empty dictionary , emptied just one operation.

Delete a dictionary with the del command, the following examples:

Examples

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
 
del dict['Name']  # 删除键是'Name'的条目
dict.clear()      # 清空字典所有条目
del dict          # 删除字典
 
print "dict['Age']: ", dict['Age'] 
print "dict['School']: ", dict['School']

But this raises an exception, because there is no longer with the del dictionaries:

dict['Age']:
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print "dict['Age']: ", dict['Age'] 
TypeError: 'type' object is unsubscriptable

Key characteristics of the dictionary

There is no limit value may be , a standard or user-defined objects , but not the key.

Two important points to remember:

1) does not allow the same key appears twice. When you create If the assigned the same key twice, the last value will be remembered , the following examples:

Examples

#!/usr/bin/python
 
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'} 
 
print "dict['Name']: ", dict['Name']

Examples of the above output:

dict['Name']:  Manni

2) key must not be changed, it can be numbers, strings, or act as a tuple, it will not work with the list, the following examples:

Examples

#!/usr/bin/python
 
dict = {['Name']: 'Zara', 'Age': 7} 
 
print "dict['Name']: ", dict['Name']

Examples of the above output:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    dict = {['Name']: 'Zara', 'Age': 7} 
TypeError: list objects are unhashable

Dictionary built-in functions & methods

Function: The Name of the class to call;

Methods: Object xxx.xx () to call;

Python dictionary contains the following built-in functions:

No. Functions and Description
1 cmp (dict1, dict2)
to compare two elements in the dictionary.
2 len (dict)
calculated total number of dictionary elements, i.e. bond.
3 str (dict)
string dictionary printable output representation.
4 type (variable)
returns the type of input variables, if the variable is a dictionary returns a dictionary.

Python dictionary contains the following built-in method:

No. Functions and Description
1 dict.clear ()
All elements in the deleted dictionary
2 dict.copy ()
Returns a shallow copy of the dictionary
3 dict.fromkeys (seq [, val])
creates a new dictionary, the sequence elements do seq dictionary key, val a dictionary initial value corresponding to all keys
4 dict.get (key, default = None)
Returns the specified key, if the return value is not in the dictionary default value
5 dict.has_key (key)
if the key is in the dictionary dict returns true, otherwise returns false
6 dict.items ()
to return may traverse the list (key, value) tuples array
7 dict.keys ()
to return a list of all the keys dictionary
8 dict.setdefault (key, default = None)
and get () is similar, but if the key does not exist in the dictionary, and will add value to default keys
9 dict.update (dict2)
to dict2 dictionary of key / value pairs in the update to the dict
10 dict.values ()
all values in the list returned dictionary
11 pop (key [, default])
value of a given key to delete the dictionary corresponding to the key, the return value is deleted. key value must be given. Otherwise, return default values.
12 popitem ()
to go back and delete the last pair of keys and values in the dictionary.
Original articles published 0 · won praise 0 · Views 112

Guess you like

Origin blog.csdn.net/weixin_44151772/article/details/104032596