A dictionary of Python Learning Notes (v) 2

Source: Internet
Author: User
Tags delete key numeric value shallow copy stdin

A dictionary of Python Learning Notes (v) 2
Often used in practical programming.
Example 1:copy

>> ad = {"name": "WTF", "hig": "180"}
>> BD = AD
>> BD
{' name ': ' WTF ', ' hig ': ' 180 '}
>> ID (AD)
4539954352
>> ID (BD)
4539954352
Description: An object affixed with two tags, using the assignment to achieve the so-called "fake copy."
If you use Copy ()
>> cd = Ad.copy ()
>> CD
{' name ': ' WTF ', ' hig ': ' 180 '}
>> ID (CD)
4541831160
Description: The CD obtained this time is different from the original AD.
If I modify the CD, it should have no effect on the original ad, as follows:
>> cd["name"] = "Didi"
>> CD
{' name ': ' Didi ', ' hig ': ' 180 '}
>> AD
{' name ': ' WTF ', ' hig ': ' 180 '}
If I modify the BD, then the ad should also change, as follows:
>> bd["name"] = "AAA"
>> BD
{' name ': ' AAA ', ' hig ': ' 180 '}
>> AD
{' name ': ' AAA ', ' hig ': ' 180 '}

About shallow and deep copies in Python
Shallow copy
Example 2: A tuple contains a list

>> x = {"Name": "WTF", "Lang": ["Python", "Java"]}
>> type (x)
<type ' Dict ' >
>> y = x.copy ()
>> y
{' lang ': [' python ', ' Java '], ' name ': ' WTF '}
>> ID (x)
4529826624
>> ID (y)
4529826344
Description: Y is copied from X, and the two are different objects in memory.
Now the value of the key "Lang" is a list, for [' Python ', ' Java '], which removes one of the elements "Java" with the Remove () List method. After deletion, the list becomes: [' Python '], as follows:
>> y["lang"].remove ("Java")
>> y
{' lang ': [' python '], ' name ': ' WTF '}
According to instance 1, it is another object, and X should not be changed:
>> x
{' lang ': [' python '], ' name ': ' WTF '}
X unexpectedly changed!!
Below we use ID () to analyze the following:
>> ID (x)
4529826624
>> ID (y)
4529826344
Description: X, y does correspond to two different objects, but the object (dictionary) is made up of two key values, one of which is a list of key values.
>> ID (x["lang"])
4529661856
>> ID (y["lang"])
4529661856
Description: The list is actually the same object!!
Explanation of Reason:
In the copy action that Python performs, if it is a primitive type of object (a numeric value and a string), it will build a nest in memory, and if it is not the base type, it will not build a new nest, but instead use the label to refer to the original nest.

Deep copy
The deep copy in Python is to import a module using import.
Example 3:

>> Import Copy
>> z = copy.deepcopy (x)
>> Z
{' lang ': [' python '], ' name ': ' WTF '}
>> ID (x["lang"])
4529661856
>> ID (z["lang"])
4529828136
Description: It was a new nest, not a quote!
At this point, if you modify one of them, you should not affect the other.
Example 4:
>> x
{' lang ': [' python '], ' name ': ' WTF '}
>> x["lang"].remove ("Python")
>> x
{' lang ': [], ' name ': ' WTF '}
>> Z
{' lang ': [' python '], ' name ': ' WTF '}

Clear
Description: In interactive mode, using Help () is a good habit.
Clear is an operation that clears all the elements in the dictionary
Example 5:

>> x
{' lang ': [], ' name ': ' WTF '}
>> X.clear ()
>> x
{}
Description: Empty the dictionary and get an "empty" dictionary.
Del () deletes the dictionary, without it in memory, not for "null".
Example 6:
>> y
{' lang ': [], ' name ': ' WTF '}
>> del (y)
>> y
Traceback (most recent):
File "<stdin>", line 1, in <module>
Nameerror:name ' y ' is not defined

Get,setdefault
The meaning of Get is:
Help (Dict.get)
Get (...)
D.get (K[,d]), D[k] if k in D, else D. D defaults to None.
Description: "If k in D" returns its value
Example 7:

>> D
{' lang ': ' Python '}
>> d.get ("Lang")
' Python '
Description: Dict.get () is to get the value of a key in the dictionary, in fact,
>> d["Lang"]
' Python '
can also be obtained.
However, if it is a value that does not exist, then:
Example 8:
>> print D.get ("name")
None
>> d["Name"]
Traceback (most recent):
File "<stdin>", line 1, in <module>
Keyerror: ' Name '
Note: This is the difference between dict.get () and dict["key".

There is a half sentence in front, and if the key is not in the dictionary, it will return none, which is a case. You can also do this:
Example 9:

>> D
{' lang ': ' Python '}
>> newd = d.get ("name", "Didi")
>> newd
' Didi '
>> D
{' lang ': ' Python '}
Description: In the way of D.get ("name", "Didi"), if the value of the key "name" cannot be obtained, the value specified later "Didi" is returned. This is the meaning of the document D.get (K[,d]), D[k] if k in D, else D. Doing so does not affect the original dictionary.

SetDefault
Help (Dict.setdefault)
Meaning: D.setdefault (K[,d]), D.get (K,d), also set D[k]=d if K not in D
Description: Similar to the function of get.
Example 10:

>> D
{' lang ': ' Python '}
>> d.setdefault ("Lang")
' Python '
>> D.setdefault ("name", "Didi")
' Didi '
>> D
{' lang ': ' Python ', ' name ': ' Didi '}
Note: There is no "name" key, so it returns D.setdefault ("name", "Didi") to the specified value "Didi" and adds the key value to "name": "Didi" to the original dictionary.

If this is the case:
Example 11:

>> d.setdefault ("Web")
>> Print D
{' lang ': ' Python ', ' web ': None, ' name ': ' Didi '}
Description: Key "web" value changed to "None"

Items/iteritems,keys/iterkeys,values/itervalues
Description: No longer required in Pytho3: iteritems,iterkeys,itervalues
? ~ Python--version
Python 2.7.10

>> Help (Dict.items)
Items (...)
D.items (), List of D ' s (key, value) pairs, as 2-tuples
Example 12:
>> dd = {"name": "WTF", "lang": "Java", "Web": "Www.datagrand.com"}
>> dd_kv = Dd.items ()
>> dd_kv
[(' Lang ', ' Java '), (' Web ', ' www.datagrand.com '), (' name ', ' WTF ')]
Description: This operation is very helpful for loops.

>> Help (Dict.iteritems)
Iteritems (...)
D.iteritems () A iterator over the (key, value) items of D
Example 13:
>> DD
{' lang ': ' Java ', ' web ': ' www.datagrand.com ', ' name ': ' WTF '}
>> dd_iter = Dd.iteritems ()
>> type (dd_iter)
<type ' Dictionary-itemiterator ' >
>> Dd_iter
<dictionary-itemiterator Object at 0x106f56a48>
>> List (Dd_iter)
[(' Lang ', ' Java '), (' Web ', ' www.datagrand.com '), (' name ', ' WTF ')]
Description: The resulting type of dd_iter, is a "dictionary-itemiterator" type, but this type of iterator data can not be directly output, you must use the list () to see the true colors inside.
The other two groups are similar in meaning to Item/iteritems.

Pop,popitem
Description: In the list, the function pop and remove for removing elements from the list are: List.remove (x) is used to delete the specified element, and List.pop[i] is used to delete the element of the specified index, and the last one is deleted by default if the index value is not provided.
In the dictionary, there are also functions to delete key-value pairs

>> Help (Dict.pop)
Pop (...)
D.pop (K[,d])-V, remove specified key and return the corresponding value.
If key is no found, D is returned if given, otherwise keyerror is raised
where D.pop (K[,d]) is a key-value pair that deletes the specified key as a parameter of the dictionary key.
Example 14:
>> DD
{' lang ': ' Java ', ' web ': ' www.datagrand.com ', ' name ': ' WTF '}
>> dd.pop ("name")
' WTF '
>> DD
{' lang ': ' Java ', ' web ': ' www.datagrand.com '}
It is worth noting that the parameters of the pop function in the dictionary cannot be omitted, which is different from the pop in the list.
Example 15:
>> Dd.pop ()
Traceback (most recent):
File "<stdin>", line 1, in <module>
Typeerror:pop expected at least 1 arguments, got 0

If you delete a key-value pair that is not in the dictionary, you will get an error:
Example 16:

>> DD
{' lang ': ' Java ', ' web ': ' www.datagrand.com '}
>> dd.pop ("name")
Traceback (most recent):
File "<stdin>", line 1, in <module>
Keyerror: ' Name '

Popitem

>> Help (Dict.popitem)
Popitem (...)
D.popitem (), (k, v), remove and return some (key, value) pair as a
2-tuple; But raise Keyerror if D is empty.
Description: D.popitem () is similar to List.pop ().
Example 17:
>> DD
{' lang ': ' Java ', ' web ': ' www.datagrand.com '}
>> Dd.popitem ()
(' Lang ', ' Java ')
>> DD
{' Web ': ' www.datagrand.com '}
Description: Randomly delete a pair
>> Dd.popitem ()
(' Web ', ' www.datagrand.com ')
>> DD
{}
The dictionary has become empty and then deleted:
>> Dd.popitem ()
Traceback (most recent):
File "<stdin>", line 1, in <module>
Keyerror: ' Popitem (): Dictionary is empty '
Description: Tell me there is nothing to delete.

Update
Description: Update dictionary

>> Help (Dict.update)
Update (...)
D.update ([E,]**f), None. Update D from Dict/iterable E and F.
If E present and has A. Keys () method, Does:for k in e:d[k] = E[k]
If E present and 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]
Description: The function does not return a value, or the return value is none, and its function is to update the dictionary. The argument can be a dictionary or an object of some kind that can be iterated.
Example 18:
>> D1 = {"Lang": "Python"}
>> D2 = {"name": "WTF"}
>> D1.update (D2)
>> D1
{' lang ': ' Python ', ' name ': ' WTF '}
>> D2
{' name ': ' WTF '}
Description: Dictionary d2 updated into the D1 that dictionary, so D1 in a few more content, D2 content included in, D2 content remains unchanged.
You can also update it in the following way:
Example 19:
>> D2
{' name ': ' WTF '}
>> d2.update ([("Song", "Xingxing"), ("Web", "www.baidu.com")])
>> D2
{' Web ': ' www.baidu.com ', ' name ': ' WTF ', ' song ': ' Xingxing '}

Has_key
Description: Currently only exists in Python2, Python3 cancels it
The function is to determine if a key exists in the dictionary, similar to "K in D".

>> Help (Dict.has_key)
Has_key (...)
D.has_key (k)-True if D has a key k, else False
Example 20:
>> D2
{' Web ': ' www.baidu.com ', ' name ': ' WTF ', ' song ': ' Xingxing '}
>> D2.has_key ("Web")
True

A dictionary of Python Learning Notes (v) 2

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.