Python dictionary and python beginners
A dictionary consists of multiple keys and their corresponding values (the key-value pair is an item). Each key and its value are separated by a colon, items are separated by commas (,), and the entire dictionary is enclosed by a pair of braces. The empty dictionary consists of two braces :{}
Dict Functions
You can use dict functions to create a dictionary through other mappings or sequences such as keys and values.
Copy codeThe Code is as follows:
>>> Items = [('name', 'gumby'), ('age', 42)]
>>> D = dict (items)
>>> D
{'Age': 42, 'name': 'gumby '}
>>> D ['name']
'Gumby'
Dict functions can also create dictionaries Using Keyword parameters:
Copy codeThe Code is as follows:
>>> D = dict (name = 'gumby', age = 42)
>>> D
{'Age': 42, 'name': 'gumby '}
Basic dictionary operations:
The basic behavior of the dictionary is similar to that of the sequence in many aspects:
Len (d) returns the number of key-value pairs in d.
D [k] returns the value associated with the key k.
D [k] = v associate the value v with the key k
Del d [k] delete key k
K in d check whether d contains k-key items
Note:
Key type: the keys in the dictionary are not necessarily set to integer data, or they may be of other immutable types.
Auto-add: even if the key does not exist in the dictionary at the beginning, you can assign a value to it so that the dictionary creates a new item, the value cannot be associated with an index outside the list range.
Membership: expression k in d (d is a dictionary) searches for keys rather than values. Expression v in l (l is a list) is used to find the value, rather than Index
Dictionary Method:
1. clear
The clear method clears all the items in the dictionary. This is an in-situ operation, so no return value is returned.
Copy codeThe Code is as follows:
>>> D = {}
>>> D ['name'] = 'gumby'
>>> D ['age'] = 42
>>> D
{'Age': 42, 'name': 'gumby '}
>>> Return_value = d. clear ()
>>> D
{}
>>> Print return_value
None
Consider the following two situations:
Copy codeThe Code is as follows:
>>> X = {}
>>> Y = x
>>> X ['key'] = 'value'
>>> Y
{'Key': 'value '}
>>> X = {}
>>> Y
{'Key': 'value '}
>>>
>>> X = {}
>>> Y = x
>>> X ['key'] = 'value'
>>> Y
{'Key': 'value '}
>>> X. clear ()
>>> Y
{}
2. copy
The copy method returns a new dictionary with the same key-value pairs (this method implements shortest copy)
Copy codeThe Code is as follows:
>>> X = {'username': 'admin', 'machines ': ['foo', 'bar', 'baz']}
>>> Y = x. copy ()
>>> Y ['username'] = 'mlh'
>>> Y ['machines ']. remove ('bar ')
>>> Y
{'Username': 'mlh', 'machines ': ['foo', 'baz']}
>>> X
{'Username': 'admin', 'machines ': ['foo', 'baz']}
From the code above, we can see that the original dictionary is not affected when the value is replaced in the copy. However, if a value is modified, the original dictionary will also change.
One way to avoid this problem is to use deep replication to copy all the values it contains. You can use the deepcopy function of the copy module to complete the operation:
Copy codeThe Code is as follows:
>>> From copy import deepcopy
>>> D = {}
>>> D ['names'] = ['alfred ', 'bertrand']
>>> C = d. copy ()
>>> Dc = deepcopy (d)
>>> D ['names']. append ('clive ')
>>> C
{'Names': ['alfred ', 'bertrand', 'clive']}
>>> Dc
{'Names': ['alfred ', 'bertrand']}
3. fromkeys
The fromkeys method creates a new dictionary using the given key. The default value of each key is None.
Copy codeThe Code is as follows:
>>>{}. Fromkeys (['nmae', 'age'])
{'Age': None, 'nmae': None}
4. get
The get method is a more loose Method for accessing dictionary items. Generally, an error occurs when you try to access an item that does not exist in the dictionary:
Copy codeThe Code is as follows:
>>> D = {}
>>> Print d ['name']
Traceback (most recent call last ):
File "<pyshell #77>", line 1, in <module>
Print d ['name']
KeyError: 'name'
>>> Print d. get ('name ')
You cannot use get.
Simple database example using get
Copy codeThe Code is as follows:
People = {
'Alice ':{
'Phone': '123 ',
'Add': 'foo drive 23'
},
'Beth ':{
'Phone': '123 ',
'Add': 'bar street 42'
},
'Cecil ':{
'Phone': '123 ',
'Add': 'baz avenue 90'
}
}
Labels = {
'Phone': 'phone number ',
'Add': 'address'
}
Name = raw_input ('name :')
# Query the phone number or address?
Request = raw_input ('phone number (p) or address ()? ')
# Use the correct key:
Key = request
If request = 'P': key = 'phone'
If request = 'A': key = 'addr'
Person = people. get (name ,{})
Label = labels. get (key, key)
Result = person. get (key, 'not available ')
Print "% s's % s is % s." % (name, label, result)
>>>================================== RESTART ==== ======================================
>>>
Name: Gumby
Phone number (p) or address ()? Batting average
Gumby's batting average is not available.
5. has_key
The has_key method can check whether the dictionary contains the given key. The expression d. has_key (k) is equivalent to the expression k in d.
Copy codeThe Code is as follows:
>>> D = {}
>>> D. has_key ('name ')
False
>>> D ['name'] = 'Eric'
>>> D. has_key ('name ')
True
6. items and iteritems
The items method returns all dictionary items in the list. Each item in the list comes from (Key, value), but there is no special order for the items to be returned.
Copy codeThe Code is as follows:
>>> D = {'title': 'python website', 'url': 'http: // www.python.org ', 'spam': 0}
>>> D. items ()
[('Url', 'HTTP: // www.python.org '), ('spam', 0), ('title', 'python website')]
The iteritems method works roughly the same but returns an iterator object instead of a list:
Copy codeThe Code is as follows:
>>> It = d. iteritems ()
>>> It
<Dictionary-itemiterator object at 0x0280F6F0>
>>> List (it)
[('Url', 'HTTP: // www.python.org '), ('spam', 0), ('title', 'python website')]
7. pop
The pop method is used to obtain the value corresponding to the given key, and then remove the key-value pair from the dictionary.
Copy codeThe Code is as follows:
>>> D = {'X': 1, 'y': 2}
>>> D. pop ('x ')
1
>>> D
{'Y': 2}
8. popitem
The popitem method is similar to list. pop. The latter will pop up the last element of the list. However, popitem pops up random items.
Copy codeThe Code is as follows:
>>> D = {'title': 'python website', 'url': 'http: // www.python.org ', 'spam': 0}
>>> D
{'Url': 'http: // www.python.org ', 'spam': 0, 'title': 'python website '}
>>> D. popitem ()
('Url', 'HTTP: // www.python.org ')
>>> D
{'Spam': 0, 'title': 'python website '}
9. setdefault
The setdefault method is similar to the get method to some extent. In addition, setdefault can also set the corresponding key value without a given key in the dictionary.
Copy codeThe Code is as follows:
>>> D = {}
>>> D. setdefault ('name', 'n'/')
'N'/'
>>> D
{'Name': 'n'/'}
>>> D ['name'] = 'gumby'
>>> D. setdefault ('name', 'n'/')
'Gumby'
>>> D
{'Name': 'gumby '}
10. update
The update method can use one dictionary item to update another dictionary:
Copy codeThe Code is as follows:
>>> D = {
'Title': 'python Web site ',
'Url': 'http: // www.python.org ',
'Changed ': 'mar 14 22:09:15 MET 2008'
}
>>> X = {'title': 'python Langue website '}
>>> D. update (x)
>>> D
{'Url': 'http: // www.python.org ', 'changed': 'mar 14 22:09:15 MET 2008 ', 'title': 'python Langue website '}
11. values and itervalues
The values method returns the value in the dictionary in the form of a list (itervalues return value iterator). Unlike the return key list, the returned value list can contain repeated elements:
Copy codeThe Code is as follows:
>>> D = {}
>>> D [1] = 1
>>> D [2] = 2
>>> D [3] = 3
>>> D [4] = 1
>>> D. values ()
[1, 2, 3, 1]
Getting started with the python dictionary
A1. the dictionary (dict), set is unordered, -- there is no order
A2/A3. common dictionary operations include:
D [key] ==> in dictionary d by key;
D. get (key, invalidvalue) ==> value by key in dictionary d. If the key does not exist in the dictionary, invalidvalue is returned. The default value is None;
D. keys ()/d. iterkeys () => return the key list of dictionary d.
D. values ()/d. itervalues () => return the Value List of dictionary d.
D. items ()/d. iteritems () ==> return the key-Value List of dictionary d.
The python dictionary key value can be a function.
Def funca ():
Pass
Def funcb (B ):
Pass
Def funcc (C ):
Pass
Def funcd (D ):
Pass
A, B, c, d = 1, 2, 3, 4
Funcdict = {a: funca, B: funcb, c: funcc, d: funcd}
Funcdict [a] (A) # = funca ()