Create and access a dictionary in python

1, the dictionary creation

(1)} and {created by the dictionary dict ()

>>> a = {'name':'gjr','age':32,'job':'dataAnalysize'}
>>> b = dict(name='gjr',age=32,job='dataAnalyze')
>>> a
{'name': 'gjr', 'age': 32, 'job': 'dataAnalysize'}
>>> b
{'name': 'gjr', 'age': 32, 'job': 'dataAnalyze'}
>>> c = dict([("name","gjr"),("age",32)])
>>> c
{'name': 'gjr', 'age': 32}
>>> d = {}
>>> e = dict()

(2)) to create a dictionary object by zip (

>>> k = ['name','age','job']
>>> v = ['gjr',32,'teacher']
>>> d =dict(zip(k,v))
>>> d
{'name': 'gjr', 'age': 32, 'job': 'teacher'}

(3) create value empty dictionary by fromkeys

>>> a = dict.fromkeys(['name','age','job'])
>>> a
{'name': None, 'age': None, 'job': None}

 

 

2, the dictionary access

(1) Access by [Key] 'value'. If the key does not exist, an exception is thrown

>>> d
{'name': 'gjr', 'age': 32, 'job': 'teacher'}
>>> d['name']
'gjr'
>>> d['aa']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'aa'

(2) obtained by the get () method 'value'. Recommended Use. Advantages are: the absence of the specified key, returns None, can also set the default object returned key does not exist.

>>> d
{'name': 'gjr', 'age': 32, 'job': 'teacher'}

>>> d.get('age')
32
>>> d.get('aa','donot known')
'donot known'

(3) a list of all key-value pairs

>>> d
{'name': 'gjr', 'age': 32, 'job': 'teacher'}

>>> d.items()
dict_items([('name', 'gjr'), ('age', 32), ('job', 'teacher')]

(4) List of all keys, all values ​​are listed

>>> d
{'name': 'gjr', 'age': 32, 'job': 'teacher'}

>>> d.keys()
dict_keys(['name', 'age', 'job'])
>>> d.values()
dict_values(['gjr', 32, 'teacher'])

(5) len () to get the number of key-value pairs

(6) detecting whether or not a [key] in the dictionary

>>> d
{'name': 'gjr', 'age': 32, 'job': 'teacher'}

>>> 'name' in d
True

Guess you like

Origin www.cnblogs.com/gaojr/p/12129940.html