Python--dict detailed

Source: Internet
Author: User

python3.0 above, the print function should be print () and there is no dict.iteritems () function.

Writing Chinese comments in Python will cause an error, as long as you add # CODING=GBK to your head

#字典的添加, delete, modify operations
Dict = {"A": "Apple", "B": "Banana", "G": "Grape", "O": "Orange"}
dict["W"] = "Watermelon"
Del (dict["a"])
Dict["g"] = "Grapefruit"
Print Dict.pop ("B")
Print Dict
Dict.clear ()
Print Dict
#字典的遍历
Dict = {"A": "Apple", "B": "Banana", "G": "Grape", "O": "Orange"}
For K in Dict:
Print "dict[%s] ="% k,dict[k]
Use of #字典items ()
Dict = {"A": "Apple", "B": "Banana", "C": "Grape", "D": "Orange"}
#每个元素是一个key和value组成的元组, output as a list
Print Dict.items ()
#调用items () Implementing a dictionary traversal
Dict = {"A": "Apple", "B": "Banana", "G": "Grape", "O": "Orange"}
For (K, V) in Dict.items ():
Print "dict[%s] ="% K, V
#调用iteritems () Implementing a dictionary traversal
Dict = {"A": "Apple", "B": "Banana", "C": "Grape", "D": "Orange"}
Print Dict.iteritems ()
For K, V in Dict.iteritems ():
Print "dict[%s] ="% K, V
For (K, v) in Zip (Dict.iterkeys (), Dict.itervalues ()):
Print "dict[%s] ="% K, V

#使用列表, dictionary as the value of the dictionary
Dict = {"A": ("apple",), "Bo": {"B": "Banana", "O": "Orange"}, "G": ["Grape", "Grapefruit"]}
Print dict["a"]
Print dict["a"][0]
Print dict["Bo"]
Print dict["Bo" ["O"]
Print dict["G"]
Print dict["G"][1]

Dict = {"A": "Apple", "B": "Banana", "C": "Grape", "D": "Orange"}
#输出key的列表
Print Dict.keys ()
#输出value的列表
Print dict.values ()
#每个元素是一个key和value组成的元组, output as a list
Print Dict.items ()
Dict = {"A": "Apple", "B": "Banana", "C": "Grape", "D": "Orange"}
it = Dict.iteritems ()
Print it
#字典中元素的获取方法
Dict = {"A": "Apple", "B": "Banana", "C": "Grape", "D": "Orange"}
Print Dict
Print Dict.get ("C", "Apple")
Print Dict.get ("E", "Apple")
Equivalent statement of #get ()
D = {"Key1": "Value1", "Key2": "Value2"}
If "Key1" in D:
Print d["Key1"]
Else
Print "None"
#字典的更新
Dict = {"A": "Apple", "B": "Banana"}
Print Dict
Dict2 = {"c": "Grape", "D": "Orange"}
Dict.update (DICT2)
Print Dict
Equivalent statement of #udpate ()
D = {"Key1": "Value1", "Key2": "Value2"}
E = {"Key3": "Value3", "Key4": "Value4"}
For K in E:
D[K] = E[k]
Print D
#字典E中含有字典D中的key
D = {"Key1": "Value1", "Key2": "Value2"}
E = {"Key2": "Value3", "Key4": "Value4"}
For K in E:
D[K] = E[k]
Print D
#设置默认值
Dict = {}
Dict.setdefault ("a")
Print Dict
Dict["a"] = "apple"
Dict.setdefault ("A", "default")
Print Dict
Sort #调用sorted ()
Dict = {"A": "Apple", "B": "Grape", "C": "Orange", "D": "Banana"}
Print Dict
#按照key排序
Print sorted (Dict.items (), Key=lambda d:d[0])
#按照value排序
Print sorted (Dict.items (), Key=lambda d:d[1])
#字典的浅拷贝
Dict = {"A": "Apple", "B": "Grape"}
Dict2 = {"c": "Orange", "D": "Banana"}
Dict2 = Dict.copy ()
Print Dict2

#字典的深拷贝
Import Copy
Dict = {"A": "Apple", "B": {"G": "Grape", "O": "Orange"}}
Dict2 = Copy.deepcopy (dict)
Dict3 = Copy.copy (dict)
dict2["B" ["g"] = "Orange"
Print Dict
dict3["B" ["g"] = "Orange"
Print Dict

Add:
1 initialization
>>> d = dict (name= ' Visaya ', age=20)
>>> d = dict (Zip ([' Name ', ' age '], [' Visaya ', 20])

#dict. Fromkeys (Listkeys, default=0) assigns the element in Listkeys as key to value and defaults to 0
>>> d = Dict.fromkeys ([' A ', ' B '], 1)
>>> D
{' A ': 1, ' B ': 1}
2 Dictionary View and geometry
Dict.keys () similar to a messenger can perform set operations such as intersection and set (similar to a collection, because there are no duplicates), but dict.values () cannot do as above.


>>> k = D.keys ()
>>> K
Dict_keys ([' A ', ' B '])
>>> List (k)
[' A ', ' B ']
>>> k | {' X ': 3}
{' A ', ' X ', ' B '}
>>> k | {' X '}
{' A ', ' X ', ' B '}
>>> k | {' x ', ' Y '}
{' A ', ' Y ', ' B ', ' X '}
>>> K & {' X '}
Set ()
>>> v = d.values ()
>>> V
Dict_values ([1, 2])
>>> V | {' X '}
Traceback (most recent):
File "<stdin>", line 1, in <module>
typeerror:unsupported operand type (s) for |: ' Dict_values ' and ' set '
3 Sort Dictionary Keys
Two methods:
3.1 Sort:
>>> Ks = List (D.keys ())
>>> Ks.sort ()
>>> for K in Ks:
... print (k, d[k])
...
A 1
B 2
3.2 Sorted:
>>> for K in Sorted (D.keys ()):
... print (k, d[k])
...
A 1
B 2

3.3 Note
>>> for K in list (D.keys ()). Sort ():
... print (k, d[k])
...
Traceback (most recent):
File "<stdin>", line 1, in <module>
TypeError: ' Nonetype ' object is not iterable


Cause of Error:
The List.sort () List.append () function operates on its own, with no return value, so the results of list (D.keys ()) must be saved and sort () on the result.
4 Common functions
4.1 Get ()
D.get (k[, d]) = D[k] If k in D else D defaults to none.
4.2 Pop ()
D.pop (value[, d]) = Remove specified key and return the corresponding value. If key is not found, and D is returned if given, otherwise keyerror is raised.
4.3 udpate ()
D.update (E, **f), None. Update D from Dict/iterable E and F.
If E has A. Keys () method, Does:for k in e:d[k] = E[k]
If E lacks. Keys () method, Does:for (K, v) in e:d[k] = V
In either case, this is followed By:for k in f:d[k] = F[k]

>>> d = dict (name= ' Visaya ', age=21)
>>> d1= {' age ': $, ' sex ': ' Male '}
>>> d2 = Zip ([' A ', ' B '], [1, 2])


>>> d.update (D1)
>>> D
{' Age ': ' ' name ': ' Visaya ', ' sex ': ' Male '}
#for k in d1:d[k] = D1[k]


>>> D.update (D2)
>>> D
{' Age ': ' ' name ': ' Visaya ', ' sex ': ' Male '}
#for (k, v) in d2:d[k] = V
4.4 del ()
Del D[key]
4.5 Clear ()
4.6 Copy ()
The dict in Python
Initialization
Construction method Creation
Python code
D = dict ()
D = dict (name= "Nico", age=23)
D = dict ([' Name ', "Nico"], [' Age ', 23])
Of course there are more convenient, simple
Python code
D = {}
D = {"Name": "Nico", "Age": 23}


Traverse
Through the traversal of the key, traversing the entire dict

Python code
D = {"Name": "Nico", "Age": 23}
For key in D:
Print "key=%s, value=%s"% (key, D[key])

For key in D.iterkeys ():
Print "key=%s, value=%s"% (key, D[key])

For key in D.keys ():
Print "key=%s, value=%s"% (key, D[key])

For key in Iter (d):
Print "key=%s, value=%s"% (key, D[key])

For Key,item in D.items ():
Print "key=%s, value=%s"% (key, item)

Of course, you can also traverse value directly

Python code
D = {"Name": "Nico", "Age": 23}
For value in D.values ():
Print value

For Key,value in D.viewitems ():
Print "key=%s, value=%s"% (key, value)

For value in D.viewvalues ():
Print "value=%s"% (value)
The difference between values and viewvalues here

The latter returns a View object of the dictionary, similar to the view in the database, when the dict changes, the View object changes as well.

Common methods

Python code
D = {"Name": "Nico", "Age": 23}
d["name"] = "AAAA"
d["Address"] = "ABCDEFG ...."
Print d #{' age ':, ' name ': ' AAAA ', ' address ': ' ABCDEFG ... '}


Get Dict value
Python code
Print d["name"] #nico
Print D.get ("name") #nico

If key is not in Dict, return default, None
Python code
Print D.get ("Namex", "AAA") #aaa
Print D.get ("Namex") #None

Sort sorted ()
Python code
D = {"Name": "Nico", "Age": 23}
For key in Sorted (d):
Print "key=%s, value=%s"% (key, D[key])
#key =age, value=23
#key =name, Value=nico


Delete del
Python code
D = {"Name": "Nico", "Age": 23}
Python code
Del d["name"]
#如果key不在dict中, throw Keyerror
del d["Names"]
Python code
Traceback (most recent):
File "F:\workspace\project\pydev\src\ddd\ddddd.py", line @ <module>
del d["Names"]
Keyerror: ' Names '


Clear Clear ()
Python code
D = {"Name": "Nico", "Age": 23}
D.clear ()
Print D #{}

Copy ()
Python code
D1 = d.copy () #{' age ':, ' name ': ' Nico '}
#使用返回view对象
D2 = D1.viewitems () #dict_items ([' Age ', ') ', (' name ', ' Nico ')])
#修改字典d1, new elements
D1["CC"] = "aaaaaa"
Print D2
#dict_items ([' CC ', ' aaaaaa '), (' Age ', ' + '), (' Name ', ' Nico ')])


Pop (key[, default])
If key is returned in Dict, the default is not returned
Python code
#如果key在dict中, returning, not returning default
Print D.pop ("name", "Niccco") #nico
Print D.pop ("namezzz", "Niccco") #niccco
#key不在dict中, and the default value is not, throw Keyerror
Print D.pop ("namezzz") #此处抛出KeyError

Popitem ()
Delete and return any one (key,value) team in Dict if the dictionary is empty will throw Keyerror
Python code
D = {"Name": "Nico", "Age": 23}
Print D.popitem () # (' Age ', 23)
Print D.popitem () # (' Name ', ' Nico ')
#此时字典d已为空
Print D.popitem () #此处会抛出KeyError

Update ([other])
Adds an element from the dictionary to Dict, and the key repeats with the value in other overrides
Python code
D = {"Name": "Nico", "Age": 23}
D2 = {"Name": "Jack", "ABCD": 123}
D.update (D2)
Print d #{' ABCD ': 123, ' age ': $, ' name ': ' Jack '}

Python--dict detailed

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.