Dictionary
dictionary
Python uses {} or dict() creates an empty dictionary:
{} dict()
Type(a
Dict
After you have dict, you can add elements to them by using the index key values, or you can view the values of the elements by index:
Insert key value:
a["one"] = "This is number 1" a["both"] = "This was number 2" a{' one ': ' This is number 1 ', ' both ': ' This is number 2 '}
Dictionaries have no order
When we have print a dictionary, Python does not necessarily appear in the order in which the key values are inserted, because the keys themselves in the dictionary are not necessarily ordered.
In Python, it is not possible to view the values in a dictionary sequentially by using a numeric index, and the number itself may become a key value, which can cause confusion
The key must be of immutable type
For hash purposes, the keys in Python that require these key-value pairs must be immutable, and the value can be any Python object.
In addition to the usual definition, dictionaries can be dict() generated through conversions:
Inventory = dict (' foozelator ', 123), (' Frombicator ', '), (' Spatzleblock '), ( ' Snitzelhogen ', ]) inventory{' foozelator ': 123, ' frombicator ': +, ' snitzelhogen ': +, ' Spatzleblock ': 34}
popmethod to delete an element
popMethod can be used to pop up values for a key in a dictionary, and you can specify default parameters:
`d.pop(key, default = None)`
Deletes and returns the value corresponding to the key in the dictionary key , and returns the default specified value if there is no key (default is None ).
A.pop ("one") ' This was number 2 ' a{' one ': ' This is number 1 '}
updateMethod Update Dictionary
person = {}person[' first ') = "jmes" person[' last '] = "Maxwell" person[' born ') = 1831print person{' born ': 1831, ' last ': ' Maxw Ell ', ' first ': ' Jmes '} #把 ' first ' changed to ' James ', while inserting ' middle ' value ' clerk ': person_modifications = {' First ': ' James ', ' Middle ': ' Clerk '}person.update (person_modifications) print person{' middle ': ' Clerk ', ' Born ': 1831, ' last ': ' Maxwell ', ' first ': ' James '}
inWhether the key is in the query dictionary
' XX ' in dictionary
keysMethod
valuesMethods and
itemsMethod
Returns a list consisting of all keys;
Returns a list consisting of all values;
Returns a list of all the key-value pairs of tuples;
Barn.keys () [' Cows ', ' cats ', ' Dogs ']barn.values () [1, 3, 5]barn.items () [(' Cows ', 1), (' Cats ', 3), (' Dogs ', 5)]
Python----------Dictionary