Several methods of dictionary in python

Source: Internet
Author: User
Php Chinese network (www.php.cn) provides the most comprehensive basic tutorial on programming technology, introducing HTML, CSS, Javascript, Python, Java, Ruby, C, PHP, basic knowledge of MySQL and other programming languages. At the same time, this site also provides a large number of online instances, through which you can better learn programming... Create a dictionary

>>> phonebook={'Alice':'2897','Alan':'0987','Jery':'6754'}

Dict functions

>>> items=[('name','Gumby'),('age',42)]>>> d=dict(items)>>> d{'age': 42, 'name': 'Gumby'}>>> d['name']'Gumby'>>> d=dict(name='July',age=24)>>> d{'age': 24, 'name': 'July'}

Basic dictionary operations (mostly similar to sequences)

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 value v to k

Del d [k] delete key k

K in d check whether d contains the key k

Format a string

>>> phonebook{'Jery': '6754', 'Alice': '2897', 'Alan': '0987'}>>> "Alan's phone number is %(Alan)s." % phonebook"Alan's phone number is 0987."

Method:

Clear all items in the dictionary

>>> D ={}>> d ['name'] = 'Gumby' >>> d ['age'] = 42 >>>> d {'age ': 42, 'name': 'Gumby'} >>> d. clear () >>> d {}>>> x ={}>> y = x # x and y correspond to the same dictionary >>> x ['key'] = 'value' >>> y {'key ': 'value' >>>> x ={}# x is associated with the new empty dictionary >>> y {'key ': 'value' >>>> x ={}>> y = x >>>> x ['key'] = 'value' >>>> y {'key ': 'value' }>>> x. clear () >>> y {}

Copy returns a new dictionary with the same key-value pairs)

>>> X = {'name': 'admin', 'machines ': ['foo', 'bar', 'bax'] >>> y = x. copy () >>> y ['name'] = 'yhk '# replace the value. The original dictionary is not affected >>> y ['machines']. remove ('bar') # Modify a value (the original dictionary is changed)> y {'name': 'yhk ', 'machines ': ['foo', 'bax '] >>> x {'name': 'admin', 'machines': ['foo', 'bax ']}

Deep copy

>>> from copy import deepcopy>>> d={}>>> d['name']=['Aly','Bob']>>> c=d.copy()>>> e=deepcopy(d)>>> d['name'].append('Ageal')>>> c{'name': ['Aly', 'Bob', 'Ageal']}>>> e{'name': ['Aly', 'Bob']}

Fromkeys creates a new dictionary using the given key. the default value of each key is none.

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

Get

>>> d={}>>> print d['name']Traceback (most recent call last):  File "
 
  ", line 1, in 
  
       print d['name']KeyError: 'name'>>> print d.get('name')None>>> d.get('name','N/A')'N/A'>>> d['name']='Eric'>>> d.get('name')'Eric'
  
 

Has_key: Check whether the dictionary has a given key (python3.0 does not have this function)

>>> d={}>>> d.has_key('name')False>>> d['name']='Eric'>>> d.has_key('name')True

Items and iteritems

Items returns all Dictionary items in the list. Each of these list items comes from (key, value)

Iteritems returns an iterator object

>>> d={'title':'My Time!','url':'http://www,python.org','spam':0}>>> d.items()[('url', 'http://www,python.org'), ('spam', 0), ('title', 'My Time!')]>>> s=d.iteritems()>>> s
 
  >>> list(s)[('url', 'http://www,python.org'), ('spam', 0), ('title', 'My Time!')]
 

Keys and iterkeys keys return the keys in the dictionary to iterkeys in the form of a list and return the iterator for the keys

Pop removal

>>> d={'x':1,'y':2}>>> d.pop('x')>>> d{'y': 2}

Popitem remove random items

>>> d={'x':1,'y':2}>>> d.popitem()('y', 2)>>> d{'x': 1}

Setdefault: if the key does not exist, the default value is returned and the corresponding dictionary is updated.

>>> d={}>>> d.setdefault('name','N/A')'N/A'>>> d{'name': 'N/A'}>>> d['name']='Gumby'>>> d.setdefault('name','N/A')'Gumby'>>> d{'name': 'Gumby'}

Update updates another dictionary using one dictionary item

>>> d={'x':1,'y':2,'z':3}>>> f={'y':5}>>> d.update(f)>>> d{'y': 5, 'x': 1, 'z': 3}

Values and itervalues alues return values in the dictionary (itervalues return value iterator)

>>> d={}>>> d[1]=1>>> d[2]=2>>> d[3]=3>>> d.values()[1, 2, 3]

The above is a detailed description of several methods in the python dictionary. For more information, see other related articles in the first PHP community!

Related Article

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.