The results of the data dictionary table

Data dictionary table form is like? What can operate? Dictionary tables and lists like, but what specific difference?

Dictionary table statement

  1. {By 'key 1': the value 'key 2': value, ...}
emp = {'name':'mike', 'age': 20, 'job': 'dev'}
  1. Note that keys need not quoted by dict dict function (key = value)
emp=dict(name= 'mike', age = 20, job = 'dev')

When a key is defined in the dictionary table, must not use the type of change (no change in situ), such as a combination of string values, but not with a listing

d['name']
d['name1']

Obtain

emp['name']
emp.get('name')

emp.get('Name',0.0)#找不到则结果显示0.0

In situ change

  1. If you want to add a button, you can use emp.update method:
dep = {'department' : 'ABC'}

emp.update(dep)
  1. To reduce a key, a method may be utilized emp.pop:
emp.pop('age')

View keys and values

emp.keys()

emp.values()

emp.items()

The result returned is not a list, you can not be python3 default list of all operations, but can traverse:

for k in emp.keys(): print(k)

for v in emp.values(): print(v)

for k,v in emp.items(): print('{} => {}'.format(k, v))

If there is a dictionary table nested case:

emp = {'name': {'first': 'mike', 'last' : 'jerry'},'age': 20, 'job': 'dev'}

emp.get('name')

emp['name']['first']

Sequence

Python 3.6 has rewritten the internal algorithm dict, so dict 3.6 is ordered, before this release, are all out of order

  1. The keys () into the list
d= {'a': 1, 'b':2}

ks = list(d.keys())

ks.sort()

for k in ks: print(d.get(k))
  1. Use global function sorted, it can be used in the iterables
d= {'a': 1, 'b':2}

ks = d.keys()

for k in sorted(ks):

print(k, d.get(k))
Released three original articles · won praise 0 · Views 56

Guess you like

Origin blog.csdn.net/shizi_yjx/article/details/104441237